Advertisement
darekfive

Remove Duplicates - Unlimited Length Match

Mar 2nd, 2025
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.60 KB | None | 0 0
  1. class Solution {
  2.     public String removeDuplicates(String s) {
  3.         Stack<Character> stack = new Stack<>();
  4.         for (int i =0; i < s.length(); i++) {
  5.             char c = s.charAt(i);
  6.             if (!stack.isEmpty() && stack.peek() == c) {
  7.                 while(i + 1< s.length() && s.charAt(i+1) == c) i++;
  8.                 stack.pop();
  9.                 continue;
  10.             } else {
  11.                 stack.push(c);
  12.             }
  13.         }
  14.         StringBuilder sb = new StringBuilder();
  15.         for (char c : stack) {
  16.             sb.append(c);
  17.         }
  18.         return sb.toString();
  19.     }
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement