WAP to Remove Consecutive Duplicate Characters from String

This Java program aims to remove consecutive duplicate characters from a given string. It utilizes a stack data structure to achieve this.

Remove Consecutive Duplicate Characters from String

package com.softwaretestingo.interviewprograms;
import java.util.Stack;
public class InterviewPrograms39 
{
	/*
	 * Input string : weelccoommee hhoommeee 
	 * Output string : welcome home
	 */
	public static void main(String[] args) 
	{
		String s = "weelccoommee hhoommeee";
		Stack<Character> st = new Stack<>();
		st.push(s.charAt(0));
		for (int i = 1; i<s.length(); i++ ) 
		{
			if (s.charAt(i-1) != s.charAt(i))
				st.push(s.charAt(i));
		}
		for ( Character c : st )
			System.out.print(c) ;
	}
}

Output

welcome home

Alternative 1:

This Java program aims to remove consecutive duplicate characters from a given input string using regular expressions.

package com.softwaretestingo.interviewprograms;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class InterviewPrograms39_1 
{
	/*
	 * Input string : weelccoommee hhoommeee 
	 * Output string : welcome home
	 */
	public static void main(String[] args) 
	{
		String s = " weelccoomme hhommeee " ;
		Pattern pattern = Pattern.compile("(.)\\1*");
		Matcher m= pattern.matcher ( s ) ;
		String output = "";
		while ( m.find())
		{
			output= output + m.group().charAt(0);
		}
		System.out.println ( output ) ;
	}
}

Output

welcome home

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment