LeetCode Solutions
1047. Remove All Adjacent Duplicates In String
Time: $O(n)$ Space: $O(n)$
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;
}
};
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();
}
}