栈模拟 : 遍历 c o m m a n d command command 的所有字符,记作 x x x 。 x x x 是 ′ G ′ 'G' ′G′ , a n s + = ′ G ′ ans+=~'G' ans+= ′G′ 。 x x x 不是 ′ ) ′ ')' ′)′ 则压栈 x x x ; x x x 是 ′ ) ′ ')' ′)′ , 则匹配栈顶的字符,匹配一个字符,弹栈一个,遇到 ′ a ′ 'a' ′a′ , c n t A cntA cntA++,直到栈顶为 ′ ( ′ '(' ′(′ 停止匹配。如果 c n t A cntA cntA 为 0 0 0 , a n s + = ′ o ′ ans+=~'o' ans+= ′o′ ,否则 a n s + = ′ a l ′ ans+=~'al' ans+= ′al′。
考虑到昨天的打卡题,一时手痒,想用栈来做今天的题。当然这题直接匹配也很简单,思路和栈模拟大致相似。
class Solution {
public:
string interpret(string command) {
string ans="";
int cntA=0;
for(auto x:command){
if('a'==x) cntA++;
else if(')'==x){
if(cntA){
ans+="al";
cntA=0;
}
else ans+='o';
}
else if('G'==x) ans+=x;
}
return ans;
}
};
class Solution {
public:
string interpret(string command) {
stack <char> stk;
//遇到G,ans+=G;遇到),统计当前匹配,其他字符压栈。
string ans="";
for(auto x:command){
int cntA = 0;
if('G'==x) ans +=x;
else if(')'==x) {//遇到')'弹栈匹配
if(stk.top()=='l') stk.pop();
if(stk.top()=='a'){
stk.pop();
cntA++;
}
if(stk.top()=='('){
stk.pop();//弹出'('
if(cntA) ans+="al";
else ans+="o";
}
}
else stk.push(x);//其他字符
}
return ans;
}
};
理解思路很重要!
欢迎读者在评论区留言,作为日更博主,看到就会回复的。

