算法Valid Parentheses (in java)
Description:Given a string s 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.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([)]"
Output: false
Example 5:
Input: s = "{[]}"
Output: true
Constraints:
1 <= s.length <= 104
s consists of parentheses only '()[]{}'.
After trying to finish this problem,I did solve the question with a not very good way.And I found a better solution on Internet.
- class Solution {
- public boolean isValid(String s) {
- Stack<Character> x = new Stack<Character>();
- for(int i = 0; i < s.length(); i++){
- //判断,如果为左侧符号,压入栈中(先进后出)
- //检查字符用“==”,检查String用“isEqual()”
- if(s.charAt(i) == '{')
- x.push('}');
- else if(s.charAt(i) == '[')
- x.push(']');
- else if(s.charAt(i) == '(')
- x.push(')');
- else if(x.size() == 0 || x.pop() != s.charAt(i))
- return false;
- }
- return x.size() ==0;
-
- }
- }
Quote:https://blog.csdn.net/yang_csdnForOBTS/article/details/79769746

浙公网安备 33010602011771号