我目前正在研究 Cracking the Coding Interview,我正在寻找一些关于我可以做些什么来纠正这个算法的建议。它似乎适用于某些测试用例,但它不适用于作为输入的测试用例 ['a','a','a','b','b','b]。任何想法我做错了什么?谢谢!
预期结果 = ['a','b']
实际结果 = ['a']
/**
* Removes duplicate chars
*
* @param str
*/
public static void removeDuplicates(char[] str) {
if (str.length < 2) {
return;
}
for (int i = 0; i < str.length; i++) {
for (int j = 0; j < str.length; j++) {
if ((str[i] == str[j]) && (i != j)) {
str[j] = 0;
}
}
}
}
尝试这样做:
public static void removeDuplicates(char[] str) {
if (str.length < 2) {
return;
}
for (int i = 0; i < str.length; i++) {
for (int j = 0; j < str.length; j++) {
System.out.println(i + "-" + j + " = " + str[j]); //added this line
if ((str[i] == str[j]) && (i != j)) {
str[j] = 0;
}
}
}
}
我为什么要给你看这个?这将向您展示删除过程的过程,并帮助您更好地了解问题。它实际上工作正常。
我不知道你是怎么得到结果的,因为没有打印语句,也没有return
语句。但是我确实找到了一种无需使用另一个char
数组(或任何与此相关的数组)的方法。它只是重建str
. 一探究竟:
public static void main(String[] args) {
char[] chr = {'a','a','b','c','b','a','b','c'};
System.out.println(removeDuplicates(chr));
}
public static char[] removeDuplicates(char[] str) {
if (str.length < 2) {
return null;
}
for (int i = 0; i < str.length; i++) {
for (int j = 0; j < str.length; j++) {
if ((str[i] == str[j]) && (i != j)) {
str[j] = 0;
}
if (i == (str.length-1)) {
str[i] = str[j];
}
}
}
return str;
}
这个例子给出了输出:
abc
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句