题目要求:
给定一个由小写和大写英文字母组成的字符串 s。
一个好的字符串是没有两个相邻字符 s[i] 和 s[i + 1] 的字符串,其中:0 <= i <= s.length - 2
s[i] 是小写字母,s[i + 1] 是相同的字母,但为大写字母,反之亦然。
为了使字符串变好,您可以选择使字符串变坏的两个相邻字符并将其删除。 您可以继续这样做,直到字符串变得良好为止。
做好后返回字符串。 在给定的约束下,保证答案是唯一的。
请注意,空字符串也很好。
Example 1:
Input: s = "leEeetcode" Output: "leetcode" Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".
Example 2:
Input: s = "abBAcC" Output: "" Explanation: We have many possible scenarios, and all lead to the same answer. For example: "abBAcC" --> "aAcC" --> "cC" --> "" "abBAcC" --> "abBA" --> "aA" --> ""
Example 3:
Input: s = "s" Output: "s"
思路
第一反应是用双指针去存储新的result字符串,然后发现当删除之后新的对可能会碰到一起(Example 2)。这个时候因为已经遍历过之前的字符,就会变得无法操作。
在ai的提醒下想到用栈的方法来操作。代码如下:
代码
class Solution {
public:
string makeGood(string s) {
vector<char> result;
for (char& c : s) {
if (!result.empty() && abs(c - result.back()) == 32) {
result.pop_back();
} else {
result.push_back(c);
}
}
return string(result.begin(), result.end());
}
};