给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。
在 S 上反复执行重复项删除操作,直到无法继续删除。
在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
示例:
输入:“abbaca”
输出:“ca”
解释:
例如,在 “abbaca” 中,我们可以删除 “bb” 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 “aaca”,其中又只有 “aa” 可以执行重复项删除操作,所以最后的字符串为 “ca”。
提示:
1 <= S.length <= 20000
S 仅由小写英文字母组成。
来源:力扣(LeetCode)
- 1
用栈简单 - 2
当时想用字符数组,但考虑到返回是string,这个思路没实现。
瞄到一个代码,用string写的.这个resize()真是妙。
class Solution {
public:
string removeDuplicates(string S) {
int top=0;
for(auto a:S){
if(!top||S.at(top-1)!=a){
S[top++]=a;
}else top--;
}
S.resize(top);
return S;
}
};
附 resize()官方解释:
void resize (size_t n);
void resize (size_t n, char c);
Resizes the string to a length of n characters.
If n is smaller than the current string length, the current value is shortened to its first n character, removing the characters beyond the nth.(把长变短,从左到右)
If n is greater than the current string length, the current content is extended by inserting at the end as many characters as needed to reach a size of n. If c is specified, the new elements are initialized as copies of c, otherwise, they are value-initialized characters (null characters).(短的不够凑成长的,用c或者null来凑)