• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
村雨sup
自己选的路,跪着也要走完 XD
博客园    首页    新随笔    联系   管理    订阅  订阅
Leetcode 20
//嘻嘻,垃圾的我写了一个小时,各种bug,丑的要死
class
Solution { public: bool isValid(string s) { stack<char> st; if(s == "") return true; if(s[0] == ')' || s[0] == ']' || s[0] == '}') return false; st.push(s[0]); int cnt = 1; while(1){ if(st.top() == '('){ if(s[cnt] == ')'){st.pop();cnt++;} else if(s[cnt] == '['||s[cnt] == '{'||s[cnt] == '('){st.push(s[cnt++]);} else return false; } else if(st.top() == '['){ if(s[cnt] == ']'){st.pop();cnt++;} else if(s[cnt] == '['||s[cnt] == '{'||s[cnt] == '('){st.push(s[cnt++]);} else return false; } else if(st.top() == '{'){ if(s[cnt] == '}'){st.pop();cnt++;} else if(s[cnt] == '['||s[cnt] == '{'||s[cnt] == '('){st.push(s[cnt++]);} else return false; } else return false; if(cnt < s.size()&&st.empty()){st.push(s[cnt++]);} if(cnt >= s.size()) break; } if(st.empty()) return true; else return false; } };

 别人写的:差距啊!

class Solution {
public:
    bool isValid(string s) {
        stack<char> parentheses;
        for (int i = 0; i < s.size(); ++i) {
            if (s[i] == '(' || s[i] == '[' || s[i] == '{') parentheses.push(s[i]);
            else {
                if (parentheses.empty()) return false;
                if (s[i] == ')' && parentheses.top() != '(') return false;
                if (s[i] == ']' && parentheses.top() != '[') return false;
                if (s[i] == '}' && parentheses.top() != '{') return false;
                parentheses.pop();
            }
        }
        return parentheses.empty();
    }
};

 

posted on 2018-09-11 17:25  村雨sup  阅读(117)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3