Description:
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
,
determine if the input string is valid.
Note:
The brackets must close in the correct order, "()"
and "()[]{}"
are
all valid but "(]"
and "([)]"
are
not.
Solution:
Analysis and Thinking:
題目要去對於輸入的字符串,其中包含‘{‘ ’}’、‘(‘ ’)’等閉合字符,判斷字符串是否合法。合法的標準當然是要以正確的順序閉合。這是一個明顯的棧應用問題,利用stack就可以解決,例如遇到左閉合符號入棧,如果遇到了一個右閉合符號,彈出一個左閉合符號,看是否匹配,因爲閉合符號遵循最近匹配原則,因此掃描一遍字符串,就可以得出結果。
Steps:
1.遍歷字符串中每一個字符
2.若當前字符與棧頂匹配,則出棧
3.否則,將當前遍歷元素入棧
Codes:
class Solution {
public:
bool isValid(string s) {
if(s.length() == 0) //空字符串,合法
{
return true;
}
stack<char> record; //用於記錄字符串的棧
record.push(s[0]);
for(int i = 2; i < s.length(); i++)
{
if(!record.empty() && isValid_helper(record.top(), s[i])) //判斷是否有閉合符號匹配,若有,則出棧,否則將字符入棧
{
record.pop();
}
else
{
record.push(s[i]);
}
}
if(record.empty()) //判斷的標準就是,是否所有的閉合符號都被匹配
{
return true;
}
else
{
return false;
}
}
bool isValid_helper(char a, char b) //用於輔助判斷閉合符號是否匹配
{
switch(a)
{
case '(':
if (b==')')
return true;
break;
case '{':
if (b=='}')
return true;
break;
case '[':
if (b==']')
return true;
break;
default:
return false;
}
}
};
Results: