简体   繁体   English

从字符串中删除字符的所有匹配对

[英]Delete all matching pairs of a character from a string

I'm trying to make a code that deletes the repeated characters. 我正在尝试编写一个删除重复字符的代码。 For example - if we have a string "aabacdc" , we want to make it as "abd" . 例如-如果我们有一个字符串"aabacdc" ,我们希望将其设置为"abd" If the character exists twice in the string, then we delete both characters as we did in the above example. 如果字符在字符串中存在两次,那么我们将像上述示例一样删除两个字符。 The 'a' occurs 3 times in our string, so we just deleted the 2 a and left 1 remaining. 'a'在我们的字符串中出现3次,因此我们删除了2个a ,剩下1个。

What I'm trying to do in this code is use two nested for loops - first for loop to compare the first character with the other characters. 我在这段代码中尝试做的是使用两个嵌套的for循环-第一个for循环将第一个字符与其他字符进行比较。 If the character has a duplicate in the string, then just delete both the characters. 如果字符在字符串中重复,则只需删除两个字符。 How can I fix this code? 如何解决此代码?

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String str2 = input.nextLine();

    StringBuilder str = new StringBuilder(str2);

    for (int k = 0; k < str.length() - 1; k++) {
        for (int i = 1; i < str.length() - 1; i++) {
            if (str.charAt(k) == str.charAt(i)) {
                str.deleteCharAt(k);
                str.deleteCharAt(i);
            } 
        }
    }

    System.out.println(str);
}

My interpretation of what you're trying to do based on your expected output is that you want to remove characters from the string 1 pair at a time. 根据您的预期输出,我对您要执行的操作的解释是,您希望一次从字符串对中删除字符。 So if there is an odd number of a character in the string, 1 should remain, and if there's an even number 0 should remain. 因此,如果字符串中的字符为奇数,则应保留1,而如果为偶数,则应保留0。

Any time you're removing elements from a structure while you're iterating by index, you need to loop over the structure backwards, so that the index values don't shift as you delete elements. 每次在通过索引迭代时从结构中删除元素时,都需要向后循环遍历该结构,以使索引值在删除元素时不会移位。 This means you should only delete elements which the outer loop is currently at, or has already seen (ie only delete elements at indexes >= i ). 这意味着您只应删除外循环当前位于或已经看到的元素(即仅删除索引>= i元素)。

Scanner input = new Scanner(System.in);
String str = input.nextLine();
StringBuilder sb = new StringBuilder(str);

for (int i = sb.length() - 2; i >= 0; i--) {
    for (int j = i + 1; j < sb.length(); j++) {
        if (sb.charAt(i) == sb.charAt(j)) {
            sb.deleteCharAt(j);
            sb.deleteCharAt(i);
            break;
        }
    }
}

System.out.println(sb);

Ideone Demo Ideone演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM