Created
November 7, 2018 00:41
-
-
Save qiaoxu123/b95dca14f8105f5bb88c382b7ab3e195 to your computer and use it in GitHub Desktop.
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 有效字符串需满足: 左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。 示例 1: 输入: "()"
输出: true
示例 2: 输入: "()[]{}"
输出: true
示例 3: 输入: "(]"
输出: false
示例 4: 输入: "([)]"
输出: false
示例 5: 输入: "{[]}"
输出: true
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool isValid(string s) { | |
vector<char> stack; | |
stack.push_back(' '); | |
for(int i = 0;i < s.size();i++){ | |
char item = s[i]; | |
if(item == '(' || item == '[' || item == '{'){ | |
stack.push_back(item); | |
} | |
if(item == ')'){ | |
if(stack.back() != '('){ | |
return false; | |
} | |
stack.pop_back(); | |
} | |
if(item == ']'){ | |
if(stack.back() != '['){ | |
return false; | |
} | |
stack.pop_back(); | |
} | |
if(item == '}'){ | |
if(stack.back() != '{'){ | |
return false; | |
} | |
stack.pop_back(); | |
} | |
} | |
if(stack.back() != ' ') | |
return false; | |
return true; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment