算法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.

  1. class Solution {
  2. public boolean isValid(String s) {
  3. Stack<Character> x = new Stack<Character>();
  4. for(int i = 0; i < s.length(); i++){
  5. //判断,如果为左侧符号,压入栈中(先进后出)
  6. //检查字符用“==”,检查String用“isEqual()”
  7. if(s.charAt(i) == '{')
  8. x.push('}');
  9. else if(s.charAt(i) == '[')
  10. x.push(']');
  11. else if(s.charAt(i) == '(')
  12. x.push(')');
  13. else if(x.size() == 0 || x.pop() != s.charAt(i))
  14. return false;
  15. }
  16. return x.size() ==0;
  17. }
  18. }


Quote:https://blog.csdn.net/yang_csdnForOBTS/article/details/79769746

posted @ 2021-03-16 18:07  Irving88  阅读(78)  评论(0)    收藏  举报