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; }
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();
}
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.
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;
}
package stringExp;
import java.util.Scanner;
public class Adjacent {
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());
}
}
}