LeetCode 20 — Valid Parentheses(有效的括號)
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
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:
輸入: “()”
輸出: true
示例 2:
輸入: “()[]{}”
輸出: true
示例 3:
輸入: “(]”
輸出: false
示例 4:
輸入: “([)]”
輸出: false
示例 5:
輸入: “{[]}”
輸出: true
分析
用棧的資料結構來儲存括號就很容易了。左括號就入棧,有括號就出棧。字串遍歷結束時如果剛好棧空,說明匹配。
c++實現
class Solution {
public:
bool isValid(string s) {
stack<char> kuohao;
bool pipei = true;
if (s == "")
return pipei;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '(' || s[i] == '{' || s[i] == '[')
kuohao.push(s[i]);
else
{
if (!kuohao.empty())
{
if (s[i] == ')' && kuohao.top() == '(')
{
kuohao.pop();
continue;
}
else if (s[i] == ']' && kuohao.top() == '[')
{
kuohao.pop();
continue;
}
else if (s[i] == '}' && kuohao.top() == '{')
{
kuohao.pop();
continue;
}
else
{
pipei = false;
break;
}
}
else
{
pipei = false;
break;
}
}
}
if (pipei == true && !kuohao.empty() == 1)
pipei = false;
return pipei;
}
};