Check a string for consecutive repeated characters [closed]

独自空忆成欢 提交于 2019-12-19 11:58:56

问题


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

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?


回答1:


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.


来源:https://stackoverflow.com/questions/24435711/check-a-string-for-consecutive-repeated-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!