- Valid Parentheses:题目链接
基本思想
见官方解析:点击这里
AC代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| import java.util.Stack;
public class Solution { public boolean isValid(String s) { char[] arr = s.toCharArray(); Stack<Character> stack = new Stack<>(); for (int i= 0; i<arr.length; ++i) { if (arr[i] == '(' || arr[i] == '{' || arr[i] == '[') { stack.push(arr[i]); }else{ if (stack.size() == 0){ return false; } char p = stack.pop(); char match; if (arr[i] == ')') { match = '('; } else if (arr[i] == ']') { match = '['; } else { match = '{'; } if (match != p) { return false; } } } if (stack.size() != 0) { return false; } return true; }
public static void main(String[] args) { System.out.println(new Solution().isValid("()[]{}")); } }
|
pS:
源代码链接