判断括号是否符合标准
这个问题思路很简单,判断右括号能不能对的上最括号就行
堆栈是个好东西
Given a string containing just the characters
'('
, ')'
'{'
'}'
'['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order,
"()"
"()[]{}"
are all valid but "(]"
"([)]"
are not. 1 package com.rust.TestString;
2
3 import java.util.Stack;
4
5 public class ValidParentheses {
6
7 public static boolean isValid(String s) {
8 if(s.length() == 0) return true;
9 Stack<Integer> stack = new Stack<Integer>();
10 char c;
11 int temp;
12 for(int i = 0; i < s.length(); i++) {
13 c = s.charAt(i);
14 if (c == '(') stack.add(1);// store left bracket
15 else if (c == '[') stack.add(2);
16 else if (c == '{') stack.add(4);
17 else {
18 if (stack.empty()) return false;
19 if (c == ')') temp = -1; //right bracket
20 else if (c == ']') temp = -2;
21 else temp = -4;
22 if(stack.peek() + temp != 0) {
23 return false; //judge
24 } else {
25 stack.pop();
26 }
27 }
28 }
29 if (stack.isEmpty()) {
30 return true;
31 } else {
32 return false;
33 }
34 }
35
36 public static void main(String args[]){
37 String s = "()(((([][[][{}{()}]])))){}[][{}]";
38
39 System.out.println("output: " + isValid(s));
40 }
41 }