题目
Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
We repeatedly make duplicate removals on S until we no longer can.
Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique.
Example 1:
Input: “abbaca”
Output: “ca”
Explanation:
For example, in “abbaca” we could remove “bb” since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is “aaca”, of which only “aa” is possible, so the final string is “ca”.
Note:
- 1 <= S.length <= 20000
- S consists only of English lowercase letters.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string
解题思路
- 遍历字符串;
- 当前字符与返回字符串的末尾字符相等时,删除返回字符串末尾字符;否则将当前字符添加至返回字符串末尾;
- 重复遍历比较过程至全部遍历完毕。
算法实现(C++)
class Solution {
public:
string removeDuplicates(string S) {
string ret;
int sSize = S.length();
for (int i = 0; i < sSize; ++i)
{
char c = S.at(i);
if (!ret.empty() && c == ret.back())
ret.pop_back();
else
ret.push_back(c);
}
return ret;
}
};