删除 String(java) 中相邻的重复字符,即输入:aaaabbbccdbbaae 输出:abcdbae

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15635585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:20:12  来源:igfitidea点击:

Remove adjacent duplicate characters in a String(java) i.e input:aaaabbbccdbbaae output: abcdbae

javastring

提问by Abs

my code does not give expected output,but dry run works fine.please give a look where is the problem

我的代码没有给出预期的输出,但试运行工作正常。请看看问题出在哪里

public static StringBuffer singleOccurence(String s)
{
 StringBuffer sb = new StringBuffer(s);
 int length=s.length();


 for(int i=0; i< length ; i++)
 {
  for(int j=i; i<length&&j<length ; j++)
  {
    if(sb.charAt(i)!=sb.charAt(j+1)) 
         i=j+1;
    else
    sb.deleteCharAt(j+1);
   } 
 }

 return sb;
}

also gives StringIndexOutOfBounds

还给出了 StringIndexOutOfBounds

采纳答案by NPE

Your method is doing a lot of unnecessary work.

你的方法做了很多不必要的工作。

The problem can be solved by iterating over the string once and comparing each character to the one that precedes it:

可以通过遍历字符串一次并将每个字符与它前面的字符进行比较来解决这个问题:

public static StringBuilder singleOccurence(String s)
{
    StringBuilder sb = new StringBuilder();
    if (s.length() > 0) {
        char prev = s.charAt(0);
        sb.append(prev);
        for (int i = 1; i < s.length(); ++i) {
            char cur = s.charAt(i);
            if (cur != prev) {
                sb.append(cur);
                prev = cur;
            }
        }
    }
    return sb;
}

This method has linear time complexity.

该方法具有线性时间复杂度。

回答by jlordo

I would use a regex:

我会使用正则表达式:

String input = "aaaabbbccdbbaae";
String regex = "(.)(\1)+"; // matches any character followed by the same one(s)
String output = input.replaceAll(regex, "");
System.out.println(output); // abcdbae

Your method would be:

你的方法是:

public static String singleOccurence(String s) {
    return s.replaceAll("(.)(\1)+", "");
}

回答by SergeyS

Easiest way is to traverse string from end to start:

最简单的方法是从头到尾遍历字符串:

public static StringBuffer singleOccurence(String s)
{
    StringBuffer sb = new StringBuffer(s);        
    for (int i = sb.length() - 2; i >= 0; i--)
        if (sb.charAt(i) == sb.charAt(i + 1))
             sb.deleteCharAt(i + 1);
    return sb;
}

回答by Eugene

Sounds a lot like a negative lookahead to me:

对我来说听起来很像一个负面的展望:

 String input = "aaaaabbbbccccddd";
    Pattern p = Pattern.compile("(.)(?!\1)");
    Matcher m = p.matcher(input);

    while(m.find()){
        System.out.println(m.group(1));
    }

回答by Rakesh KR

Try this:

试试这个:

    String reg;
    String input;
    String output;
    reg    = "(.)(\1)+";
    input  = "aaaabbbccdbbaae";
    output = input.replaceAll(reg,"");
    System.out.println("Input :"+input);
    System.out.println("Output:"+output);

回答by zeacuss

you can use replaceAllmethod with a regex

你可以使用replaceAll带有一个的方法regex

string result = myString.replaceAll(/([a-z])+/ig, "");

what this regexdoes is that it matches any alpha character [a-z]that is repeated which is triggered by the part \1+

这样regex做是为了匹配[a-z]由零件触发的任何重复的字母字符\1+

the flags in the regex (after the last /) indicate that it should search the whole string (the gflag) and it should ignore the case (the iflag). you might not need the gflag since here we are using replaceAll.

正则表达式中的标志(在最后一个之后/)表明它应该搜索整个字符串(g标志)并且它应该忽略大小写(i标志)。您可能不需要该g标志,因为我们在这里使用replaceAll.

here, we are replacing with $1which means, replace with the first matched group. since we have parentheses around the [a-z], the $1will be the matched character.

在这里,我们用$1which 替换,用第一个匹配的组替换。因为我们在 周围有括号[a-z],所以$1将是匹配的字符。

this all ends up meaning that, find repeated characters in the string, while ignoring the case and replace them with that character.

这一切最终意味着,在字符串中找到重复的字符,同时忽略大小写并将它们替换为该字符。

回答by Griffit

public class RemoveAdjacentLetters {

公共类 RemoveAdjacentLetters {

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter any word: "); // Inputting the word
    String str = scanner.nextLine();
    for (int i = 1; i < str.length(); i++) { // from 2nd letter
        if (str.charAt(i) == str.charAt(i - 1)) { // comparing adjacent
                                                    // letters

            str = str.substring(0, i - 1) + str.substring(i + 1); // eliminating
                                                                    // 1st
                                                                    // duplicates
            System.out.println(str);
            i = 0;                // i=0 because I need to check for all possible adjacent letters.. 

        }
    }
    if (str.length() == 0) {
        System.out.println("Empty String");
    } 
    scanner.close();
}

}

}

回答by Naveen

import java.util.Arrays; import java.util.Scanner;

导入 java.util.Arrays; 导入 java.util.Scanner;

public class ReverseSkip {

公共类反向跳过{

public static void main(String[] args) {
    String str;
    Scanner in = new Scanner(System.in);
    System.out.println("Enter the Word or Sentence");
    str =in.nextLine();
    String revStr ="null";

    char [] chars = str.toCharArray();
    char [] reversedChars = new char[chars.length];

    reversedChars[reversedChars.length - 1] = chars[0];


    int r = reversedChars.length - 2;
    for(int i = 1 ; i < chars.length ; i++ ){
        if(chars[i] != chars[i-1]){
            reversedChars[r] = chars[i];
            r--;
        }
    }

    revStr = new String(Arrays.copyOfRange(reversedChars, r+1, reversedChars.length));

    System.out.println(revStr);
}

}

}

回答by Soudipta Dutta

This is easy to solve in Java. You just have to take a StringBuffer. This is the complete code:

这在 Java 中很容易解决。你只需要一个StringBuffer。这是完整的代码:

public class Test3 {
public static void main(String[] args) {
    String str = "aaaabbbccdbbaae";
    StringBuffer sbr = new StringBuffer();
    int i = 0 ;
    while(i < str.length()) {
        if(sbr.length() == 0 ) sbr.append(str.charAt(i));
        if(str.charAt(i) == sbr.charAt(sbr.length() -1)) {i++ ;}
        else {sbr.append(str.charAt(i)); i++;}
    }//while
System.out.println(sbr);
}

}//end1

This is the complete solution in Python :(Different Idea)

这是 Python 中的完整解决方案:(不同的想法)

def lis(a):
    list1 = [] 
    # put the characters in the list
    [list1.append(ch)  for ch in a]
    print(list1)
    # moving backwards from last element i.e.len(a) -1 to first element 0 and step is -1
    for i in range(len(list1) - 1 , 0 , -1):
        # delete the repeated element
        if list1[i] == list1[i - 1]: del list1[i]

    return ''.join(list1)    


a = "Protiijaayii"
# output Protijayi
print(lis(a))