问题
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.
- If you find string[i]==string[i-1]. Break the loop. Choose the next string.
- 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