牛客编程巅峰赛S1第11场 - 黄金&钻石 A.牛牛的01游戏 (模拟栈)
-
题意:有一个\(01\)串,两个相邻的\(0\)可以变成一个\(1\),两个相邻的\(1\)可以直接消除,问操作后的字符串.
-
题解:数组模拟栈直接撸,上代码吧.
-
代码:
class Solution { public: /** * * @param str string字符串 初始字符串 * @return string字符串 */ string solve(string str) { // write code here char stk[1000010]; int cnt=0; for(int i=0;i<str.size();++i){ if(cnt!=0){ if(stk[cnt]==str[i]){ if(str[i]=='0'){ //两个相邻0的情况 if(stk[cnt-1]=='1'){ //如果前一位是1,00->1后就接着上一个1,所以直接消除 cnt-=2; } else{ stk[cnt]='1'; //正常情况 } } else cnt--; //两个相邻1的情况 } else stk[++cnt]=str[i]; //0和1相邻 } else{ stk[++cnt]=str[i]; //栈为空 } } string ans=""; for(int i=1;i<=cnt;++i){ ans.push_back(stk[i]); } return ans; } };
𝓐𝓬𝓱𝓲𝓮𝓿𝓮𝓶𝓮𝓷𝓽 𝓹𝓻𝓸𝓿𝓲𝓭𝓮𝓼 𝓽𝓱𝓮 𝓸𝓷𝓵𝔂 𝓻𝓮𝓪𝓵
𝓹𝓵𝓮𝓪𝓼𝓾𝓻𝓮 𝓲𝓷 𝓵𝓲𝓯𝓮