题目链接:https://ac.nowcoder.com/acm/contest/6912/A
Description
牛牛最近迷上了小游戏,于是他也想对他的01字符串进行一些操作,01字符串上的0和0相邻时会变成1,而1和1相邻时会在字符串上消失,而0和1相邻时什么都不会发生,牛牛现在把初始的字符串给你,你能告诉牛牛这个字符串最后会变成什么样吗。
Sample
输入
“00110001”
输出
“01”
说明
00110001→1110001→10001→1101→01
PS
1≤∣str∣≤106,字符串上的合并消失应优先与左边进行,例如000,中间的0优先与左边的0合并变为10,消失同理
Solution
用一个栈来维护,遍历所给字符串,栈空将当前字符入栈,否则拿当前字符跟栈顶字符比较,不同将当前字符入栈,相同,若为字符’1’,将栈顶元素出栈,若为字符‘0’,将栈顶元素出栈,将当前字符改成字符‘1’,再拿当前字符去比较。重复以上操作即可。
AC Code
class Solution {
public:
/**
*
* @param str string字符串 初始字符串
* @return string字符串
*/
string solve(string str) {
// write code here
stack<char> s;
s.push(str[0]);
char f;
for(int i=1;i<str.length();i++){
if (!s.empty())
{
f=s.top();
if(str[i]==f){
if(f=='0') {
s.pop();
str[i]='1';
i--;
}
else s.pop();
}
else s.push(str[i]);
}
else s.push(str[i]);
}
string ans;
while(!s.empty()){
ans+=s.top();
s.pop();
}
reverse(ans.begin(),ans.end());
return ans;
}
};
觉得有帮助的话,点个赞再走吧!