[leetcode]20. Valid Parentheses有效括号序列

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. 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

题意:

给定一个括号序列,判断其是否合法。

思路:

指针i来扫给定字符串

对于字符串的每个char,若是左括号,入栈

                                 若栈不为空&&栈顶元素与对应位置的右括号匹配,出栈

代码:

 1 class Solution {
 2     public boolean isValid(String s) {
 3         Stack<Character> stack = new Stack<>();
 4         for(int i = 0; i<s.length(); i++){
 5             char c = s.charAt(i);
 6             if(c == '(' || c =='{' || c=='['){
 7                 stack.push(c);
 8             }
 9             else if( c == ')' && !stack.empty() && stack.peek() =='('){
10                 stack.pop();
11             }
12             else if( c == '}' && !stack.empty() && stack.peek() =='{'){
13                 stack.pop();
14             }
15             else if( c == ']' && !stack.empty() && stack.peek() =='['){
16                 stack.pop();
17             }
18             else{
19                 return false;
20             }
21         }
22         return stack.isEmpty();
23     }
24 }

followup:  Valid Parentheses 简化版:只有()一种括号,且input string里有别的字母,加减号。看括号是否是闭合。

)()()() ----> true
(+1^$#)(#$) ----> true
)( ----->false
(()#%33 ----->false

代码:

 1 public class valid_parenthese_modified {
 2     public boolean isValid(String s) {
 3         int count = 0;
 4         for (char c : s.toCharArray()) {
 5             if (c == '(')
 6                 count++;
 7             else if (c == ')') {
 8                 if (count == 0) // notes for the if-judge here
 9                     return false;
10                 count--;
11             }
12         }
13         return count == 0;
14     }
15 }
原文地址:https://www.cnblogs.com/liuliu5151/p/9125299.html