問題描述
給定一個只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判斷字符串是否有效。
有效字符串需滿足:
- 左括號必須用相同類型的右括號閉合。
- 左括號必須以正確的順序閉合。
注意空字符串可被認爲是有效字符串。
示例 1:
輸入: "()"
輸出: true
示例 2:
輸入: "()[]{}"
輸出: true
示例 3:
輸入: "(]"
輸出: false
示例 4:
輸入: "([)]"
輸出: false
示例 5:
輸入: "{[]}"
輸出: true
解法
使用一個棧來存儲,每當遇到匹配的括號則彈出頭元素,最終判斷棧是否爲空。
Python
class Solution:
def isValid(self, s: str) -> bool:
if len(s)==0:
return True
if len(s)%2!=0 or s[0] in ')]}':
return False
S=[]
pair={'(':')',')':'(','[':']',']':'[','{':'}','}':'{'}
for c in s:
if len(S)==0:
S.append(c)
continue
if S[-1]!=pair[c]:
S.append(c)
else:
S.pop()
return len(S)==0
C++
static const auto io_sync_off=[](){
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
bool isValid(string s) {
if(s.size()==0)return true;
if(s.size()%2==1)return false;
stack<char> S;
for(int i=0;i<s.size();i++){
if(S.empty()){
S.push(s.at(i));
continue;
}
char last=S.top();
char curr=s.at(i);
switch(last){
case '(':
if(curr!=')')
S.push(curr);
else
S.pop();
break;
case '[':
if(curr!=']')
S.push(curr);
else
S.pop();
break;
case '{':
if(curr!='}')
S.push(curr);
else
S.pop();
break;
default:
S.push(curr);
}
}
return S.empty()?true:false;
}
};