【Leetcode長征系列】Valid Parentheses

原題:

Given a string containing just the characters '(', ')','{','}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but"(]" and"([)]" are not.

思路:

首先string長度必須爲偶數,否則報錯。其次每一對括號必須在一起,否則報錯。

代碼:

class Solution {
public:
    bool isValid(string s) {
        if (s.size()%2!=0) return false;
        
        for (int j = 0; j<s.size()-1; j+=2){
            if(s[j]=='(') {
                if(s[j+1]==')') continue;
                else return false;
            }
            if(s[j]=='[') {
                if(s[j+1]==']') continue;
                else return false;
            }
            if(s[j]=='{') {
                if(s[j+1]=='}') continue;
                else return false;
            }
        }
    }
};
報錯了…

=================================================================================================================================

之前讀題有問題,後來再理解一遍後覺得,還是需要一個堆棧的。重寫代碼如下:

class Solution {
public:
    bool isValid(string s) {
        stack<char> p;
        char c;
        
        for(int i = 0; i<s.size(); i++){
            if(s[i]=='(' || s[i]=='[' || s[i]=='{')     p.push(s[i]);
            else{
                if(p.empty()) return false;
                c = p.top();
                if((s[i]==')' && c=='(')||(s[i]==']' && c=='[')||(s[i]=='}' && c=='{'))      p.pop();
                else return false;
            }
        }
        if (!p.empty()) return false;
        return true;
    }
};
但還是卡在一樣的地方了,WA…

================================================================================================================================

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


你真得沒有在逗我麼- -#

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章