Problem: 括号匹配问题。
使用栈,先进后出!
参考代码1:
package leetcode_50; import java.util.Stack; /*** * * @author pengfei_zheng * 括号匹配问题 */ public class Solution20 { public static boolean isValid(String s) { Stack<Character> stack = new Stack<>(); int len = s.length(); for(int i=0;i<len;i++){ char c = s.charAt(i); if(c=='(' || c=='{' || c=='[') stack.push(c); if(c==')'){ if(stack.isEmpty()) return false; else if('('!=stack.pop()) return false; } if(c=='}'){ if(stack.isEmpty()) return false; else if('{'!=stack.pop()) return false; } if(c==']'){ if(stack.isEmpty()) return false; else if('['!=stack.pop()) return false; } } if(!stack.isEmpty()) return false; else return true; } public static void main(String[]args){ String s="[[(])]"; System.out.println(isValid(s)); } }
参考代码2:
public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); 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(); }