Skip to content

1047. Remove All Adjacent Duplicates In String 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  string removeDuplicates(const string& S) {
    string ans;

    for (const char c : S)
      if (!ans.empty() && ans.back() == c)
        ans.pop_back();
      else
        ans.push_back(c);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public String removeDuplicates(final String S) {
    StringBuilder sb = new StringBuilder();

    for (final char c : S.toCharArray()) {
      final int n = sb.length();
      if (n > 0 && sb.charAt(n - 1) == c)
        sb.deleteCharAt(n - 1);
      else
        sb.append(c);
    }

    return sb.toString();
  }
}