Java 检查字符串中是否有连续重复的字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24435711/
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-08-14 12:11:40  来源:igfitidea点击:

Check a string for consecutive repeated characters

javastringcharacter

提问by Venki

It is asked in an interview to write the code in Java to display the string which doesn't have consecutive repeated characters.

面试要求用Java写代码,显示没有连续重复字符的字符串。

E.g.: Google, Apple, Amazon; It should display "Amazon"

例如:谷歌、苹果、亚马逊;它应该显示“亚马逊”

I wrote code to find continues repeating char. Is there any algorithm or efficient way to find it?

我写了代码来查找继续重复的字符。有什么算法或有效的方法可以找到它吗?

采纳答案by Jerky

class replace
{

public static void main(String args[])
{
    String arr[]=new String[3];
    arr[0]="Google";
    arr[1]="Apple";
    arr[2]="Amazon";
    for(int i=0;i<arr.length;i++)
    {
        int j;
        for(j=1;j<arr[i].length();j++)
        {
            if(arr[i].charAt(j) == arr[i].charAt(j-1))
            {
                break;
            }
        }
        if(j==arr[i].length())
                System.out.println(arr[i]);
    }
}
}

Logic : Match the characters in a String with the previous character.

逻辑:将字符串中的字符与前一个字符匹配。

  1. If you find string[i]==string[i-1]. Break the loop. Choose the next string.
  2. If you have reached till the end of the string with no match having continuous repeated character, then print the string.
  1. 如果你发现 string[i]==string[i-1]。打破循环。选择下一个字符串。
  2. 如果您一直到达字符串的末尾而没有匹配的连续重复字符,则打印该字符串。