'(',')','{','}','[',']' , 。
:
。
。
。
1:
: "()"
: true
2:
: "()[]{}"
: true
3:
: "(]"
: false
4:
: "([)]"
: false
5:
: "{[]}"
: true
: (LeetCode)
:https://leetcode-cn.com/problems/valid-parentheses
。 , 。
class Solution {
public boolean isValid(String s) {
Stack stack = new Stack();
for(int i = 0; i < s.length(); i++){
if(s.substring(i, i+1).equals("(") || s.substring(i, i+1).equals("[") || s.substring(i, i+1).equals("{")) stack.push(s.substring(i, i+1));
else if(stack.empty()) return false;
else if((stack.peek().equals("(") && s.substring(i, i+1).equals(")")) || (stack.peek().equals("[") && s.substring(i, i+1).equals("]")) || (stack.peek().equals("{") && s.substring(i, i+1).equals("}"))) stack.pop();
else return false;
}
if (stack.empty()) return true;
else return false;
}
}