1. 程式人生 > >[LeetCode]20 Valid Parentheses 有效的括號

[LeetCode]20 Valid Parentheses 有效的括號

parent desc ets must sam rip 而不是 ket 必須

[LeetCode]20 Valid Parentheses 有效的括號

Description

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example

Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true

題意

給定一個只包括 ‘(‘‘)‘‘{‘‘}‘‘[‘‘]‘ 的字符串,判斷字符串是否有效。
有效字符串需滿足:

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

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

題解

用棧模擬即可,註意開個map,而不是通過多次判斷可以節約時間。

代碼

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

[LeetCode]20 Valid Parentheses 有效的括號