C++ 空栈不能调用top()

题目描述(链接:https://ac.nowcoder.com/acm/contest/6912/A 来源:牛客网)

牛牛最近迷上了小游戏,于是他也想对他的01字符串进行一些操作,01字符串上的0和0相邻时会变成1,而1和1相邻时会在字符串上消失,而0和1相邻时什么都不会发生,牛牛现在把初始的字符串给你,你能告诉牛牛这个字符串最后会变成什么样吗。

采用栈实现时,当栈为空时,以为空栈调用top函数会返回NULL,然而调用时会发生段错误。
原来stack 的top函数在栈为空时返回的是超尾-1,所以

The top function returns the topmost element of the stack. You should ensure that there are one or more elements on the stack before calling the top function.

每次调用top()时最好确认一下栈是否为空或者提前压栈一个不可能出现的元素代表栈底 

class Solution {
public:
    /**
     * 
     * @param str string字符串 初始字符串
     * @return string字符串
     */
    string solve(string str) {
        // write code here
        int n = str.length();
        if(n <2)
            return str;
        string res = "";
        stack<char> note;
        note.push(str[0]);
        for(int i = 1; i < n; ++i){
            if(!note.empty()){
                if(note.top() == '0' && str[i] == '0'){
                    note.pop();
                    if(!note.empty() && note.top() == '1'){//如果栈之前还有1直接消失
                        note.pop();
                        continue;
                    }
                    note.push('1');
                    continue;
                }
                else if(note.top() == '1' && str[i] == '1'){
                    note.pop();
                    continue;
                }
            }
            note.push(str[i]);
        }
        while(!note.empty()){
            res += note.top();
            note.pop();
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

给你一颗小瓜子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值