leetcode 20 簡單括號匹配(C++和python實現)
阿新 • • 發佈:2018-11-13
【題目描述】
給定一個只包括
'('
,')'
,'{'
,'}'
,'['
,']'
的字串,判斷字串是否有效。有效字串需滿足:
- 左括號必須用相同型別的右括號閉合。
- 左括號必須以正確的順序閉合。
注意空字串可被認為是有效字串。
示例 1:
輸入: "()" 輸出: true
示例 2:
輸入: "()[]{}" 輸出: true
示例 3:
輸入: "(]" 輸出: false
示例 4:
輸入: "([)]" 輸出:false
示例 5:
輸入: "{[]}" 輸出: true
從第一個字串開始遍歷:
a.如果是左括號:直接push到棧中;
b.如果是右括號:棧的top是否和這個右括號匹配?pop() : return False;
c.字串遍歷完後,堆疊要為空!
【方法一】C++有封裝好的棧可以用:
class Solution { public: bool isValid(string s) { stack<char> my_stack; int i=0; my_stack.push('#');//哨兵 while(i<s.size()) { if(s[i]=='('||s[i]=='{'||s[i]=='[') { my_stack.push(s[i]); ++i; } else if((s[i]==')'&&my_stack.top()=='(')||(s[i]==']'&&my_stack.top()=='[')|(s[i]=='}'&&my_stack.top()=='{')) { ++i; my_stack.pop(); } else return false; } if(my_stack.top()=='#') return true; return false; } };
【Python方法】
用字典巧妙的解法,右括號作為鍵:
class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] paren_map = {')':'(',']':'[','}':'{'} for c in s: if c not in paren_map: stack.append(c) elif not stack or paren_map[c] != stack.pop(): return False return not stack