[ Title ]
Given a string str, the overall judgment is not a valid string brackets
For example, str = "()", returns true; str = "(() ())", returns true; str = "(())", returns true;
str = "())", return false; str = "() (", return false; str = "() a ()", return false;
my:
1 import java.util.Stack; 2 3 public boolean my_isValid(String str) 4 { 5 if(str == null || str.equals("")) 6 { 7 return false; 8 } 9 10 char[] cstr = str.toCharArray(); 11 Stack<Character> stack = new Stack<>(); 12 for(char c : cstr) 13 { 14 if(c == '(') 15 { 16 stack.push(c); 17 } 18 else if(c == ')') 19 { 20 if(stack.empty()) 21 { 22 return false; 23 } 24 stack.pop(); 25 } 26 else 27 { 28 return false; 29 } 30 } 31 return stack.empty() ? true : false; 32 }
Time complexity: O (N), the spatial complexity: O (N)
Left Teacher:
. 1 public Boolean isValid (String STR) 2 { . 3 IF (STR == null || str.equals ( "" )) . 4 { . 5 return to false ; . 6 } . 7 . 8 char [] = Chas str.toCharArray (); . 9 int 0 = COUNT; // simply set a counter 10 for ( char C: Chas) . 11 { 12 is IF (= C '(' && = C ')'!! ) 13 is { 14 return false; 15 } 16 if(c == ')' && --count < 0) 17 { 18 return false; 19 } 20 if(c == '(') 21 { 22 count++; 23 } 24 } 25 26 return count == 0; 27 }
Time complexity: O (N), the spatial complexity: O (1)
[Advanced] title
Given a bracket string str, returns the longest substring effective brackets
For example, str = "(() ())", returns 6; str = "())", return to 2; str = "() (() () (", returns 4
Source: Left Cheng Yun teacher "Programmer Code Interview Guide"