Leetcode 20. Valid Parentheses
2017-01-15 10:33
375 查看
20. Valid Parentheses
Given a string containing just the characters
determine if the input string is valid.
The brackets must close in the correct order,
all valid but
not.
Inspired by the stack idea, I use a string (temp) to simulate the function. If met a "(" or "[" or "{" , just append the character to temp, the other characters are“)”."]","}". If met a “)” or "]" or "}",take the last character of temp into compare, as we all
know, the ascii value 40:"(" 41:“)” 91:"[" 93: "]" 123:"{" 125:"}", So if the characters are an valid pair, the absolute difference is less than 2 .if so, just remove the last character of temp, and continue comparing the remaining ones.
Given a string containing just the characters
'(',
')',
'{',
'}',
'['and
']',
determine if the input string is valid.
The brackets must close in the correct order,
"()"and
"()[]{}"are
all valid but
"(]"and
"([)]"are
not.
Inspired by the stack idea, I use a string (temp) to simulate the function. If met a "(" or "[" or "{" , just append the character to temp, the other characters are“)”."]","}". If met a “)” or "]" or "}",take the last character of temp into compare, as we all
know, the ascii value 40:"(" 41:“)” 91:"[" 93: "]" 123:"{" 125:"}", So if the characters are an valid pair, the absolute difference is less than 2 .if so, just remove the last character of temp, and continue comparing the remaining ones.
class Solution { public: bool isValid(string s) { string temp=""; int i=0; while(i<s.size()) { if(s[i]=='('||s[i]=='['||s[i]=='{') { temp+=s[i]; i++; } else { if(temp.size()==0) return false; // temp is empty, means “)”,"]","}" has no partners else if(abs(s[i]-temp[temp.size()-1])<=2) temp=temp.substr(0,temp.size()-1); //remove the last character of temp else return false; i++; } } if(temp.size()!=0) return false; // temp is not empty, means "(" or "[" or "{" has been left else return true; } };
相关文章推荐
- leetcode_20_Valid Parentheses (easy)
- LeetCode-20. Valid Parentheses
- LeetCode 20 -- Valid Parentheses
- leetcode 20. Valid Parentheses
- 20. Valid Parentheses-leetcode-java
- [leetcode]20. Valid Parentheses(java)
- Leetcode 20. Valid Parentheses
- leetcode题解-20. Valid Parentheses
- Leetcode 20 Valid Parentheses 判断括号匹配
- [leetcode Q20] Valid Parentheses
- LeetCodet题解--20. Valid Parentheses(括号匹配问题)
- leetcode - 20.Valid Parentheses
- LeetCode20:Valid Parentheses
- [leetcode 20] Valid Parentheses
- leetcode 20. Valid Parentheses
- Leetcode_20_Valid Parentheses
- leetcode 20. Valid Parentheses
- 【LeetCode】20. Valid Parentheses
- LeetCode-20-Valid Parentheses(有效的括号)
- leetcode解题报告20. Valid Parentheses