括号匹配
package leetcode.editor.cn;
import java.util.HashMap;
import java.util.Stack;
public class ValidParentheses{
public static void main(String[] args) {
Solution solution = new ValidParentheses().new Solution();
}
class Solution {
方法一:
public boolean isValid(String s) {
if(s.length() == 0)
return true;
Stack<Character> stack = new Stack<>();
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 (s.charAt(i) == ')' && (stack.isEmpty() || stack.pop() != '('))
return false;
else if(s.charAt(i) == ']' && (stack.isEmpty() || stack.pop() != '['))
return false;
else if(s.charAt(i) == '}' && (stack.isEmpty() || stack.pop() != '{'))
return false;
}
}
if(stack.isEmpty())
return true;
else
return false;
}
}
方法二:
public boolean isValid(String s) {
if (s.length() == 0)
return true;
HashMap<Character,Character> map = new HashMap<Character, Character>();
map.put(')','(');
map.put(']','[');
map.put('}','{');
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); ++i) {
if (map.containsKey(s.charAt(i))) {
if(stack.isEmpty() || stack.pop() != map.get(s.charAt(i)))
return false;
}
else
stack.push(s.charAt(i));
}
if (stack.isEmpty())
return true;
else
return false;
}
}