https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
pair를 사용해서 몇개가 누적되는지 계속 파악해나간다. 개수와 같아지면 pop을해서 빼 버리고,
마지막에 살아있으면서 누적되어 있는 애들은 count수 만큼 더해주면 된다.
class Solution {
public:
string removeDuplicates(string s, int k) {
stack<pair<char, int>> sStack;
for (int i = 0; i < s.size(); ++i)
{
if (sStack.empty())
sStack.push(make_pair(s[i], 1));
else
{
if (s[i] == sStack.top().first)
{
sStack.top().second++;
if (sStack.top().second == k)
sStack.pop();
}
else
{
sStack.push(make_pair(s[i], 1));
}
}
}
string result;
while (!sStack.empty())
{
int count = sStack.top().second;
for (int i = 0; i < count; ++i)
{
result += sStack.top().first;
}
sStack.pop();
}
std::reverse(result.begin(), result.end());
return result;
}
};
Runtime: 20 ms, faster than 49.40% of C++ online submissions for Remove All Adjacent Duplicates in String II.
Memory Usage: 8.1 MB, less than 76.46% of C++ online submissions for Remove All Adjacent Duplicates in String II.
45~ 75까지 나온다.