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: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
思路:简单题,运用栈的后进先出特性去匹配即可,注意要排除各种意外情况
package com.Easy.Ryan;
import java.util.Stack;
public class ValidParentheses {
public static void main(String[] args) {
ValidParentheses validParentheses=new ValidParentheses();
String string= "{{)}";
System.out.println(validParentheses.isValid(string));
}
public boolean isValid(String s) {
boolean result = false;
Stack<Character> stack=new Stack<>();
Character character;
if (s.length()%2==1) {
return false;
}
if (s.length()==0) {
return true;
}
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i)=='(' || s.charAt(i)=='[' || s.charAt(i)=='{') {
stack.push(s.charAt(i));
}
else {
if (stack.isEmpty()) {
return false;
}
character=stack.pop();
if (s.charAt(i)==')'&& character=='(' || s.charAt(i)==']'&& character=='[' || s.charAt(i)=='}'&& character=='{') {
result=true;
}
else {
return false;
}
}
}
if (!stack.isEmpty()) {
result=false;
}
return result;
}
}