【发布时间】:2016-11-02 06:42:29
【问题描述】:
public static void main(String[] args)
{
char[] x = {'b', 'l', 'a', 'h', 'h', ' '};
char[] y = {'g', 'o', 'g', 'o'};
System.out.println(removeDuplicate(x, y));
System.out.println(noDuplicate(y, x));
public static char[] removeDuplicate(char[] first, char[] second)
{
//used my append method (didn't enclose) to append the two words together
char[] total1 = append(first, second);
//stores character that have been encountered
char[] norepeat = new char[total1.length];
int index = 0;
//store result
char[] solution = new char[total1.length];
boolean found = false;
//for loop keeps running until blahh gogo is over
for(int i = 0; i < total1.length; i++)
{
for(int m = 0; m <norepeat.length; m++)
{
if(total1[i] == norepeat[m])
{
found = true;
break;
}
}
if (!found)
{
norepeat[index] = total1[i];
index++;
solution[index] = total1[i];
index++;
}
}
return solution;
}
}
电流输出:
blah
go
我希望输出是:
blah go
goblah (space at the end)
我的代码的问题是它在遇到第一次重复后停止运行,所以它甚至根本没有运行整个单词。我相信这与我的嵌套 for 循环有关,但我不确定。我试着把它写在纸上,但似乎没有任何帮助。
任何帮助将不胜感激!谢谢!
【问题讨论】:
-
你在输出中最终得到
goblah的逻辑是什么? -
为什么你不使用 hashSet ?使用 HashSet 问题将在 O(N) 时间内解决。不要写已经写好的代码。
-
@TimBiegeleisen 在我打印出“System.out.println(noDuplicate(y, x));”时我现在正在从 y 到 x 读取 char[] - 因此从 gogo 到 blahh 读取。因此,在删除重复项后,我希望第二个输出是 goblah。希望我为您澄清了这一点。
-
@nikeshjoshi 我是一名初级 Java 程序员,现在正在学习我的基础知识。我还没有了解 HashSet...
-
如果您当前的输出仅输出
first的值(这似乎发生了),那么您的append()方法可能不起作用。 ---norepeat和solution有什么区别?我的意思是,除了norepeat获得分配的所有偶数索引和solution获得分配的所有奇数索引之外,因为您在if (!found)块中增加了两次index。 --- 也许你应该调试你的代码。见What is a debugger and how can it help me diagnose problems?