题目:
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
解答:
首先确定本题的思路为:使用栈
自己一开始的解题思路为:使用栈的数据结构,因为匹配的括号的话,一定是成对出现的,若将左括号一次压入栈,遇到匹配的右括号在弹出栈,则若是匹配的话,栈最后一定为空。
stack.push();向栈中添加数据
stack.peek();栈的顶部的数据
class Solution{
public static boolean isValid(String s){
if(s.length()==0){
return true;
}
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(stack.isEmpty()){
return false;
}else if((stack.peek()=='('&&c==')')||(stack.peek()=='{'&&c=='}')||(stack.peek()=='['&&c==']')){
stack.pop();
}else{
return false;
}
}
return stack.isEmpty();
}
}
后来发现了更为简便的解法:
思路为:
当碰到左括号,则压入栈的是右括号,在遇到右括号时,弹出栈,判断是否弹出的栈顶元素就是当前扫描的右括号,若不是,则不是匹配的字串,返回false,最后遍历完成后,判断栈是否为空。
class Solution {
public static boolean isValid(String s) {
if (s.isEmpty())
return true;
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}
}
另有解法:
class Solution {
public boolean isValid(String s) {
Stack<Character> stack=new Stack<Character>();
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if(stack.isEmpty()){
stack.push(c);
}else{
if(stack.peek()-c==-1||stack.peek()-c==-2){
stack.pop();
}else{
stack.push(c);
}
}
}
System.out.println(stack.size());
return stack.isEmpty();
}
}