zoukankan      html  css  js  c++  java
  • 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();
        }
    };
  • 相关阅读:
    Git:常用命令记录
    JS笔记(二):隐式转换
    vertical-align/line-height:水平垂直居中
    JS笔记(一):声明提升
    Array.prototype.sort():从一道面试题说起
    CSS笔记(一):选择器规范
    FreeCodeCamp:Profile Lookup
    tile_images_offset的简单使用
    vs2013快捷键等(转)
    Qt状态栏的使用(转)
  • 原文地址:https://www.cnblogs.com/cunyusup/p/9629069.html
Copyright © 2011-2022 走看看