【发布时间】:2017-02-20 15:31:22
【问题描述】:
这就是我想要完成的任务。我正在尝试编写一个从 2 个给定字符串执行以下操作的代码:target 和 source。
// Determines whether the string TARGET occurs as a substring of string SOURCE where "gaps" are allowed between characters of target.`
// That is, the characters in TARGET occur in SOURCE in their given order but do not have to be adjacent.`
// (Pictured another way, this method returns true if TARGET could be obtained from SOURCE by removing some of the letters of SOURCE.)`
// This method is case sensitive. For example,`
// containsWithGaps("hamburgers", "mug") returns true`
// containsWithGaps("hamburgers", "burrs") returns true`
// containsWithGaps("hamburgers", "hamburgers") returns true`
// containsWithGaps("hamburgers", "gum") returns false`
// containsWithGaps("hamburgers", "hamm") returns false`
// containsWithGaps("hamburgers", "") returns true`
// Parameters:`
// SOURCE - the given string in which to find the target characters`
// TARGET - the characters to be found`
// Returns:`
// true if the characters in TARGET can be found as a subsequence in SOURCE, false otherwise`
这是我编写的代码。对于我认为不应该是一项艰巨的任务来说,这似乎过于复杂,但无论如何,我仍然会不断收到错误,如果给定一个源字符串hamburgers 和一个目标字符串burr,它就不起作用:
public static boolean substringWithGaps(String source, String target) {
boolean substring = false;
int[] target_index;
target_index = new int [target.length()];
if (target.length() > source.length()) {
substring = false;
}
else {
for (int i = 0; i < target.length(); i++) {
if (source.contains("" + target.charAt(i))) {
target_index[i] = target.indexOf(i);
i++;
}
else {
target_index[i] = target.indexOf(i);
i++;
}
}
for (int i = 0; i < target_index.length; i++) {
if (target_index[i] == -1) {
substring = false;
break;
}
else if (target_index[i] >= target_index[i+1]) {
substring = false;
break;
}
else {
substring = true;
}
if (target_index.length != target.length()) {
substring = false;
}
}
}
return substring;
}
有什么想法吗?
【问题讨论】:
-
伪代码:
String foo = source.replace(/\s+/, "", g); if (-1 != foo.indexOf(target) { hooray() } -
只是这个
source.contains(target),在Java中可以正常工作。 -
@Jorge Campos 不,这将不满足要求 - 只有当目标完全在源中时它才会返回 true。要求是可以有中间字母,
标签: java string loops substring