This is the Java Program to Delete Adjacent Pairs of Repeated Characters.
Given a string, find and remove all the adjacent pairs of repeated characters.
Example:
String x = “ABBCCCD”
Output = “ACD”
Create a stack and push the first character of the string on it. Now, iterate through the string, and check whether the current character of the string is at the top of the stack. If it is, then pop it off the stack. Form a string from the characters left in the string and reverse it.
Here is the source code of the Java Program to Delete Adjacent Pairs of Repeated Characters. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
// Java Program to Delete Adjacent Pairs of Repeated Characters.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class AdjacentCharacters {
// Function to remove adjacent characters
static String removeAdjacentRepeatedCharacters(String str){
Stack<Character> stack = new Stack<>();
int i;
stack.push(str.charAt(0));
for(i=1; i<str.length(); i++){
if(stack.peek() == str.charAt(i)){
stack.pop();
continue;
}
stack.push(str.charAt(i));
}
StringBuffer obj = new StringBuffer();
while(!stack.isEmpty()){
obj.append(stack.pop());
}
return obj.reverse().toString();
}
// Function to read the input and display the output
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter the string");
try {
str = br.readLine();
} catch (IOException e) {
System.out.println("An I/O error occurred");
return;
}
String newString =removeAdjacentRepeatedCharacters(str);
System.out.println("The new string is \"" + newString + "\"");
}
}
1. In function removeAdjacentRepeatedCharacters(), a stack is created and the first character of the string is pushed onto the stack.
2. The loop for(i=1; i<str.length(); i++) iterates through the rest of the string.
3. The condition if(stack.peek() == str.charAt(i)) checks if the current character of the string is equal to the character at the top of the stack.
4. If it is, a character is popped from the stack otherwise the current character of the string is pushed onto the stack.
5. The loop while(!stack.isEmpty()) add all the characters of the stack to a StringBuffer object and the reverse of the object is returned.
Time Complexity: O(n) where n is the length of the string.
Case 1 (Simple Test Case): Enter the string ABBCCCD The new string is "ACD" Case 2 (Simple Test Case - another example): Enter the string XYZ The new string is "XYZ"
Sanfoundry Global Education & Learning Series – Java Programs.
- Practice BCA MCQs
- Practice Information Technology MCQs
- Apply for Java Internship
- Apply for Computer Science Internship
- Check Programming Books