您好,我正在尝试使此代码正常工作,以便当输入为诸如“ aaabbbccdddeef”之类的字符串时,输出为“ abcdef”。我知道那里有解决方案,但令我感到困扰的是这不起作用,我不知道为什么。如果有人可以帮助我理解这段代码为什么不起作用,我将非常感激。
Scanner input = new Scanner(System.in);
System.out.print("please enter the string of characters: " );
String str = input.nextLine();
char[] store = new char[str.length()];
int count =0;
for(int i=0; i<str.length();i++) {
for (int j=0; j<str.length(); j++) {
if(str.charAt(i)==store[j] ){
count+=1;//when character not stored keep count to offset store position
break;
}else {store[i-count] = str.charAt(i); count = 0;}
}
}
System.out.println(str);
System.out.print(store);
我们可以使用带有String#replaceAll
的单线满足您的要求:
String input = "aaabbbccdddeef";
String output = input.replaceAll("(.)(\\1)+", "$1");
System.out.println(input + "\n" + output);
此打印:
aaabbbccdddeef
abcdef
此处使用的正则表达式为(.)(\1)+
,它与任何单个字符匹配,后跟一个或多个相同字符。替换只是单个孤立的字符。
编辑:
如果您想继续使用迭代方法,那么逻辑应该是沿着字符串向下移动,并且仅在先前重复[[not时才将字符添加到最终输出中:
String input = "aaabbbccdddeef";
String output = "" + input.charAt(0);
char prev = input.charAt(0);
for (int i=1; i < input.length(); ++i) {
char curr = input.charAt(i);
if (curr != prev) {
output += curr;
prev = curr;
}
}
System.out.println(input + "\n" + output);
但是请注意,这实际上是我的正则表达式解决方案使用的算法,除了此版本需要更多代码行。
Scanner input = new Scanner(System.in);
System.out.print("please enter the string of characters: " );
String str = input.nextLine();
StringBuilder store = new StringBuilder ();
for(int i=0; i<str.length();i++) {
if (!store.toString().contains(Character.toString(str.charAt(i)))) {
store.append(str.charAt(i));
}
}
System.out.println(str);
System.out.print(store);
for
循环内的逻辑。您必须在第二个for循环中迭代store
而不是str
。检查我的解决方案: Scanner input = new Scanner(System.in);
System.out.print("please enter the string of characters: ");
String str = input.nextLine();
char[] store = new char[str.length()];
int count = 0;
boolean charInStore = false;
for (int i = 0; i < str.length(); i++) {
charInStore = false;
for (int j = 0; j < store.length; j++) {
if (str.charAt(i) == store[j]) {
charInStore = true;
break;
}
}
if (!charInStore) {
store[count] = str.charAt(i);
count++;
}
}
System.out.println(str);
System.out.print(store);
我的解决方案非常简单:创建一个遍历字符串整个长度的for循环然后使用+ charAt的索引确定字符串是否重复超过1创建名为temp的新字符串。然后,如果这样,则删除这些字符中的每一个,只剩下一个然后打印温度
String.indexOf('a');