Valid Parentheses

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

 1 public class Solution {
 2     public boolean isValid(String s) {
 3         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         // '(' - '0' :: -8
 5         // ')' - '0' :: -7
 6         
 7         // '[' - '0' :: 43
 8         // ']' - '0' :: 45
 9         
10         // '{' - '0' :: 75
11         // '}' - '0' :: 77
12         Stack<Integer> st = new Stack<Integer>();
13         for(int i = 0; i < s.length(); i ++){
14             int c = s.charAt(i) - '0';
15             if(c == -8 || c == 43 || c == 75) st.push(c);
16             else if(c == -7){
17                 if(st.size() != 0 && st.peek() == -8)st.pop();
18                 else return false;
19             }
20             else if(c == 45){
21                 if(st.size() != 0 && st.peek() == 43)st.pop();
22                 else return false;
23             }
24             else if(c == 77){
25                 if(st.size() != 0 && st.peek() == 75)st.pop();
26                 else return false;
27             }
28             else return false;
29         }
30         if(st.size() != 0) return false;
31         return true;
32     }
33 }
原文地址:https://www.cnblogs.com/reynold-lei/p/3371438.html