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
题目需要我们判断是否是正确的括号使用,这道题有点类似镜像串。用一个pos变量记录每次是否是对应的()[]{},如果符合则减一,如果不符合就把pos变量一直加上去直到碰到符合的括号,最后如果能削减到0说明括号的使用正确,不能则说明不正确。
1 bool isValid(char* s) { 2 int pos = 0;//记录还没排除的括号 3 for(int i=0;s[i]!='\0';i++) { 4 /*()的ASCII码差一,[]{}差二,所以在if第二个判断条件要加上一,不然()正确使用不通过,而[]{}最后就算加一整型取整了依旧等一*/ 5 if(pos && (s[i]-s[pos-1]+1)/2 == 1){ 6 pos--; 7 }else { 8 s[pos++] = s[i]; 9 } 10 } 11 return pos ? false : true; 12 }