1047. Remove All Adjacent Duplicates In String
Asked at 14Meta54Apple49Amazon34Bloomberg32Google30Microsoft23Whatnot100Grammarly97Paytm97Ripple82Geico66Deloitte50Cisco37Oracle35
Problem
Repeatedly delete two adjacent equal letters from s until no such pair remains, and return the final string (it is unique).
Example: "abbaca" → "ca"
Use the output as a stack: if the incoming char equals the top, pop; else push.
Complexity: O(n).
class Solution:
def removeDuplicates(self, s: str) -> str:
st = []
for ch in s:
if st and st[-1] == ch:
st.pop()
else:
st.append(ch)
return "".join(st)
assert Solution().removeDuplicates("abbaca") == "ca"
assert Solution().removeDuplicates("azxxzy") == "ay"
class Solution {
public String removeDuplicates(String s) {
StringBuilder st = new StringBuilder();
for (char c : s.toCharArray()) {
if (st.length() > 0 && st.charAt(st.length() - 1) == c) st.deleteCharAt(st.length() - 1);
else st.append(c);
}
return st.toString();
}
}
func removeDuplicates(s string) string {
st := []byte{}
for i := 0; i < len(s); i++ {
if len(st) > 0 && st[len(st)-1] == s[i] {
st = st[:len(st)-1]
} else {
st = append(st, s[i])
}
}
return string(st)
}