题目
https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string/
代码
class Solution {
public String removeDuplicates(String S) {
int top= -1;
int len=S.length();
StringBuffer res=new StringBuffer();
for(int i=0;i<len;i++){
if(top>=0&&res.charAt(top)==S.charAt(i)){
res.deleteCharAt(top);
top--;
}
else{
top++;
res.append(S.charAt(i));
}
}
return res.toString();
}
}
复杂度
时间复杂度:O(n),其中 n 是字符串的长度。我们只需要遍历该字符串一次。
空间复杂度:O(n) 或O(1),取决于使用的语言提供的字符串类是否提供了类似「入栈」和「出栈」的接口。注意返回值不计入空间复杂度。