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
leetcode中不需要导包
class Solution {
public boolean isValid(String s) {
Stack<Character> sk = new Stack<>();
Character c;
for(int i=0;i<s.length();i++){
c = s.charAt(i); //字符串常用函数
if(c=='('||c=='['||c=='{'){sk.push(c);}
//注意!sk.isEmpty()是为了防止字符串后面多出括号')'出现无效
else if(c==')'&&!sk.isEmpty()&&sk.peek()=='('){sk.pop();}
else if(c==']'&&!sk.isEmpty()&&sk.peek()=='['){sk.pop();}
else if(c=='}'&&!sk.isEmpty()&&sk.peek()=='{'){sk.pop();}
else{return false;}
}
return sk.isEmpty(); //栈刚好为空则正好匹配,不为空则证明字符串后面少括号
}
}