276. another zuma
You are joining another zuma game, the following is its rules:
There is a pearl sequence, and one character on every pearl.
Every kk pearls with the same character listed together, they will be removed.
After each step of removing, the left pearls will unite to a new sequence.
Please calculate what will remain finally after removing.
Example
Input:
"abbaca"
2
Output:
"ca"
Clarification
In the example, "abbaca" -> "aaca" -> "ca".
Notice
The number of pearls will be nn, 1≤n≤10^5
Every kk same pearl together will be removed, 2≤k≤10^5
All the characters on pearls will be lowercase English character.
It's guaranteed that the answer will be only.
解法1:用stack。时间复杂度应该是O(n)。
class Solution {
public:
/**
* @param s: the pearl sequences.
* @param k: every k same pearls together will be removed.
* @return: return the pearls after the game.
*/
string zumaGaming(string &s, int k) {
stack<pair<char, int>> st; //<char, repetitive count>
string result = "";
int len = s.size();
st.push({s[0], 1});
for (int i = 1; i < len; ++i) {
if (!st.empty() && st.top().first == s[i]) {
int new_same_count = st.top().second + 1;
st.push({s[i], new_same_count});
if (new_same_count == k) {
while (new_same_count > 0) {
st.pop();
new_same_count--;
}
}
} else {
st.push({s[i], 1});
}
}
while(!st.empty()) {
result = st.top().first + result;
st.pop();
}
return result;
}
};
解法2:网上看到的做法。比较简洁。
class Solution
{
public:
/**
* @param s: the pearl sequences.
* @param k: every k same pearls together will be removed.
* @return: return the pearls after the game.
*/
string zumaGaming(string &s, int k)
{
if (s.size() < k || k <= 0)
{
return s;
}
bool del = true;
while(del)
{
del = false;
int start = 0;
int count = 1;
for (int i = 1; i < s.size(); i++)
{
if (s[i] == s[start])
{
count++;
if (count == k)
{
s.erase(start, k);
del = true;
}
}
else
{
start = i;
count = 1;
}
}
}
return s;
}
};
本文详细解析了Zuma游戏的算法实现,通过两种方法展示了如何处理珠子序列中连续重复字符的消除问题。方法一使用栈来跟踪字符及其重复次数,而方法二则通过循环检查并删除满足条件的连续重复字符。文章提供了完整的代码示例,帮助读者理解算法的具体应用。
1万+

被折叠的 条评论
为什么被折叠?



