Eliminate the pairs (two same chars adjacent to each other) in string

Problem:
You are given a string. You have to eliminate the pairs (two same chars adjacent to each other).

eg. input string RGBBGBGR –> RGGBGR–> RBGR (output)

Solution:
We should check if we have character pair then cancel it. and then check for next character and previous character. Keep canceling the character until we either reach start of the array or end of the array or not find a pair.

Implementation:

void removeAdjacentPair(char* str)
{
    int len = strlen(str);
    int i,j=0;
    for(i=1; i < len; i++)
    {
        while((str[i]==str[j]) && (j >= 0))
        {
            i++;
            j--;
        }
         
        str[++j] = str[i];
    }
    str[j+1]='\0';  
    return;
}

3 Thoughts on “Eliminate the pairs (two same chars adjacent to each other) in string

  1. public String eliminateAdjChar(String str) {
    StringBuilder result = new StringBuilder(str);
    int i = 0;
    while (i < result.length() – 1) {
    if (result.charAt(i) == result.charAt(i + 1)) {
    result.delete(i, i + 2);
    if (i != 0)
    i–;
    } else
    i++;
    }
    return result.toString();
    }

  2. Corrected the above.
    public static String removeDuplicate(String s) {
    StringBuilder result = new StringBuilder(s);
    int i = 0;
    while (i < (result.length()-1)) {
    if (result.charAt(i) == result.charAt(i + 1)) {
    result.delete(i, i + 2);

    if (i != 0){
    i–;
    }
    }
    else
    i++;
    }

    return result.toString();
    }

    Is there any other easy way in java to write this program.

  3. static StringBuffer eliminateAdjacentPair(StringBuffer strBuf){
    for(int i = 0; i < strBuf.length()-1;){
    if(strBuf.charAt(i) == strBuf.charAt(i+1)){
    strBuf.delete(i, i+2);
    i = i-1;
    continue;
    }
    i++;
    }
    return strBuf;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation