消除字符串中的重复字符

问题描述 投票:1回答:4

您好,我正在尝试使此代码正常工作,以便当输入为诸如“ 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);
java filter text-processing
4个回答
1
投票

我们可以使用带有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);
但是请注意,这实际上是我的正则表达式解决方案使用的算法,除了此版本需要更多代码行。

1
投票
另一种方法是将其附加到StringBuilder,如果它不存在的话

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);


0
投票
需要更改第二个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);


-1
投票
这可能是一个简单的解决方案,也可能是一个非常复杂的解决方案。

我的解决方案非常简单:创建一个遍历字符串整个长度的for循环然后使用+ charAt的索引确定字符串是否重复超过1创建名为temp的新字符串。然后,如果这样,则删除这些字符中的每一个,只剩下一个然后打印温度

String.indexOf('a');

© www.soinside.com 2019 - 2024. All rights reserved.