1. 程式人生 > >(LeetCode每日一刷06)有效的括號

(LeetCode每日一刷06)有效的括號

題目描述:

給定一個只包括 '('')''{''}''['']' 的字串,判斷字串是否有效。

有效字串需滿足:

  1. 左括號必須用相同型別的右括號閉合。
  2. 左括號必須以正確的順序閉合。

注意空字串可被認為是有效字串。

 

示例:

示例 1:

輸入: "()"
輸出: true

示例 2:

輸入: "()[]{}"
輸出: true

示例 3:

輸入: "(]"
輸出: false

示例 4:

輸入: "([)]"
輸出: false

示例 5:

輸入: "{[]}"
輸出: true

 

我提交的程式碼:

class Solution {
public:
    int singleCharToInt(char a)
    {
        switch(a)
        {
            case '(':
                return 1;
            case ')':
                return 6;
            case '[':
                return 5;
            case ']':
                return 2;
            case '{':
                return 3;
            case '}':
                return 4;
            default:
                return 0;
        }
    }
    
    bool isValid(string s) 
    {
        int s_length = s.size();
        
        if(s_length == 0)
        {
            return true;
        }
        
        if(s_length%2 != 0)
        {
            return false;
        }
        
        stack<int> stk;
        
        int i;
        int pre = singleCharToInt(s[0]);
        int current;
        if(pre % 2 == 0)
        {
            return false;
        }
        else
        {
            stk.push(pre);
        }
        
        for (i = 1; i < s_length; ++i)
        {
            current = singleCharToInt(s[i]);
            
            if(current % 2 == 0)
            {
                if(pre + current == 7)
                {
                    stk.pop();
                    if(stk.empty())
                    {
                        return true;
                    }
                    pre = stk.top();
                }
                else
                {
                    return false;
                }
            }
            else
            {
                stk.push(current);
                pre = current;
            }
        }
        
        if(stk.empty())
        {
            return true;
        }
        else
        {
            return false;
        }
          
    }
};

 

執行用時: 4 ms, 在Valid Parentheses的C++提交中擊敗了70.92% 的使用者