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错误。所以,我想知道我的代码有什么问题,以及如何改进它。
发布于 2020-11-19 12:10:13
这是一个正确的运行版本。注意,您还需要检查不匹配的新字符是否与最后一个目标匹配。否则duplicateLetters("axbc", "abc");就会失败。(这仍将发生在ruhul已经提出的索引修正中)。
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;
}优化:
通过
发布于 2020-11-19 11:05:46
当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.
https://stackoverflow.com/questions/64910274
复制相似问题