【发布时间】:2021-07-22 17:03:01
【问题描述】:
我正在尝试确定一个字符串是否只编辑过一次。当我输入以下字符串(见下面的代码)时,输出不正确。程序应该打印出字符串只编辑过一次,这不是我在屏幕上看到的。谁能帮帮我?
public static void main(String[] args) {
String str1 = "cat";
String str2 = "ca";
char[] arr1 = str1.toCharArray();
char[] arr2 = str2.toCharArray();
int n = str1.length();
int m = str2.length();
if (stringWasEdited(str1, str2, arr1, arr2, m, n)) {
System.out.print("The string was edited only once.");
} else {
System.out.print("The string was not edited or was edited more than once.");
}
}
private static boolean stringWasEdited(String str1, String str2, char[] arr1, char[] arr2, int m, int n) {
int count = 0;
if (Math.abs(m - n) > 1) {
return false;
}
for (int i = 0; i < m; i++) {
if (arr1[i] != arr2[i]) {
count++;
}
if (m > n || n > m) {
count++;
}
}
if (count > 1 || count == 0) {
return false;
}
return true;
}
}
【问题讨论】:
-
更多常规任务请查看Levenshtein Distance