public class DuplicateLetters {
// CW2.2 Lab-Group-06 Question 5
// You are given two non-empty strings source and target, all lowercase letters, from a user.
// The user intends to type the string given in target.
// However, due to using an old keyboard,
// when the user was typing, a number characters may be duplicated, and typed one or more times.
// The source is what the user actually typed, which may or may not be the intended target.
// Return true if and only if it is possible that some characters of target have been duplicated in source,
// while the user intended to type the target string.
// You must use String methods in lecture notes.
// You must NOT use StringBuilder or Regular Expression methods.
public static boolean duplicateLetters(String source, String target) {
boolean test = false;
for(int i=0; i<source.length(); i++) {
for(int j=i; j<target.length(); j++) {
if(Character.toString(source.charAt(i)).equals(Character.toString(target.charAt(j)))) {
test = true;
}
else {
test = false;
j--;
}
i++;
}
}
return test;
}
public static void main(String[] args) {
System.out.println(duplicateLetters("andddrew", "andrew"));
// true, there are duplicated letters typed
System.out.println(duplicateLetters("lllejiiee", "leejie"));
// false, note the initial letter e
// there is only one initial e in the source, whereas there is a double initial ee in the target
System.out.println(duplicateLetters("cherry", "cherry"));
// true, no duplicated letters typed this time
}
这是我针对这个问题的代码,但它一直得到java.lang.StringIndexOutOfBounds错误。所以,我想知道我的代码有什么问题,以及如何改进。
这是一个正确的运行版本。请注意,您还需要检查不匹配的新字符是否与目标的最后一个字符匹配。否则CCD_ 1将失败。(这仍然会发生在鲁胡尔已经提出的指数修复中(。
public static boolean duplicateLetters(String source, String target) {
int i = 0;
char lastTargetChar = target.charAt(0);
for(int j=0; j<target.length(); j++) {
while ( source.charAt(i) != target.charAt(j)) {
// we only go in here if the char in source is wrong, thus assume a dupe, but check if it's a dupe!
if (lastTargetChar != source.charAt(i)) {
return false;
}
i++;
if (i >= source.length()) {
return false;
}
}
// if we end here, source char was found ok, so remember last char and go to next char in source
lastTargetChar = target.charAt(j);
i++;
}
return true;
}
优化:
- 在目标上循环,以便更容易地检查目标中的双字母(例如"letter"one_answers"lettttter"(
- 出现问题时立即退出循环。你不需要继续,因为结果在任何情况下都是正确的
当i
的值超过发生的source.length
异常时,您正在内部循环中递增值i。
for(int j=i; j<target.length(); j++) {
if(Character.toString(source.charAt(i)).equals(Character.toString(target.charAt(j)))) {
test = true;
}
else {
test = false;
j--; // you don't need to decrement the value of j.
}
i++; // problematic code.
}
要解决此问题,请在比较或中断循环之前添加一个检查。例如:
...
i++; // break the loop so that i remains consistent.
if(i>=source.length()) break;
此外,您的逻辑过于复杂和错误。由于修复这些错误超出了范围,所以你应该自己找(作业(:P