# 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;
}
```

### 4 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.

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;
}

4. Abhinay Tiwari on October 9, 2017 at 10:41 am said:

package stringExp;

import java.util.Scanner;

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(“enter String”);
Scanner sc = new Scanner(System.in);
String s = sc.next();
StringBuffer sb = new StringBuffer(s);
for (int i = 0; i < sb.length() – 1; i++) {
if (sb.charAt(i) == sb.charAt(i + 1)) {

sb.delete(i, i + 2);
i = 0;
}
if (sb.length() == 2) {
sb.replace(i, i + 2, " ");
}
}
if (sb.length() == 0) {
System.out.println("empty string");
} else {
System.out.println(sb.toString());

}
}
}