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