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

时间:2022-06-27 04:39:08

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,若是左括号,入栈

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

代码:

 class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(int i = 0; i<s.length(); i++){
char c = s.charAt(i);
if(c == '(' || c =='{' || c=='['){
stack.push(c);
}
else if( c == ')' && !stack.empty() && stack.peek() =='('){
stack.pop();
}
else if( c == '}' && !stack.empty() && stack.peek() =='{'){
stack.pop();
}
else if( c == ']' && !stack.empty() && stack.peek() =='['){
stack.pop();
}
else{
return false;
}
}
return stack.isEmpty();
}
}

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

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

代码:

 public class valid_parenthese_modified {
public boolean isValid(String s) {
int count = 0;
for (char c : s.toCharArray()) {
if (c == '(')
count++;
else if (c == ')') {
if (count == 0) // notes for the if-judge here
return false;
count--;
}
}
return count == 0;
}
}