[Leetcode 20] 20 Valid Parentheses

Problem:

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.

Analysis:

Use a stack to help. If the element is '(', '[', '{', push it onto stack. If the element is ')', ']', '}', pop one element from stack and see if they match with each other. If not match, then return false;

Other cases may cause false result are: 1.  Meet with ')', ']', '}', but the stack is empty; 2. The string has been processed, but the stack is not empty.

The time complexity is O(n), the space complexity is O(n) in worst case, O(1) in best case; 

Code:

 1 public class Solution {
 2     public boolean isValid(String s) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         char[] stack = new char[100];
 6         int tos = 0;
 7         char tmp;
 8         
 9         for (int i=0; i<s.length(); ++i) {
10             tmp = s.charAt(i);
11             switch(tmp) {
12                 case '(': case '[': case '{': stack[tos++] = tmp; break;
13                 case ')': 
14                     if (tos==0 || stack[--tos]!='(') 
15                             return false;
16                     break;
17                 case '}': 
18                     if (tos==0 || stack[--tos]!='{') 
19                             return false;
20                     break;    
21                 case ']': 
22                     if (tos==0 || stack[--tos]!='[') 
23                         return false;
24                     break;
25             }
26         }
27      
28         if (tos != 0)
29             return false;
30         else
31             return true;
32     }
33 }
View Code

Attention:

原文地址:https://www.cnblogs.com/freeneng/p/3086476.html