描述:
Given a string 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.
Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: trueExample 2:
Input: "()[]{}" Output: trueExample 3:
Input: "(]" Output: falseExample 4:
Input: "([)]" Output: falseExample 5:
Input: "{[]}" Output: true
问题解答:
该问题主要就是判断一个字符串是否为有效的括号序列,其中有效的含义为
1.括号的类型需要一致,如小括号对小括号,中括号对中括号等;
2.还需要保证括号的顺序正确,如左括号对应右括号
解题思路:
采用栈来保存该字符串序列,其中遇到左括号就入栈,右括号就将栈顶出栈,判断两个括号是否对应的上
代码:
package com.zqr.leetCode;
import java.util.Stack;
public class ValidParentheses {
public boolean isValid(String s) {
if (s == null || s.length() == 0) {
return true;
}
if (s.length() % 2 != 0) {
return false;
}
Stack<Character> result = new Stack<Character>();
result.push(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case ')':
if (result.pop() != '(') {
return false;
}
break;
case '}':
if (result.pop() != '{') {
return false;
}
break;
case ']':
if (result.pop() != '[') {
return false;
}
break;
default:
result.push(c);
}
}
return result.empty();
}
public static void main(String[] args) {
System.out.println(new ValidParentheses().isValid("()"));
System.out.println(new ValidParentheses().isValid("()[]{}"));
System.out.println(new ValidParentheses().isValid("(]"));
System.out.println(new ValidParentheses().isValid("([)]"));
System.out.println(new ValidParentheses().isValid("{[]}"));
}
}