Given A string containing just the characters,,, ‘(‘ ‘)‘ , and ‘{‘ ‘}‘ ‘[‘ ‘]‘ , determine if the input string I S valid.
The brackets must close in the correct order, and is all valid but and is not "()" "()[]{}" "(]" "([)]" .
public class Solution {
if (s = = null) return false; stack<character> stack = new stack<character> (); char[] ch = s.tochararray (); for (int i = 0; i < ch.length; i++) {if (ch[i] = = ' (') | | (Ch[i] = = ' [') | | (Ch[i] = = ' {')) Stack.push (Ch[i]), else {if (Stack.isempty ()) return false;if (Ch[i]-Stack.pop () > 2) return false;} return Stack.isempty ();
public Boolean isValid (String s) { if (s = = null) //Improved 1: Can be used without string.charat (i)
return false; Improvement 2: Judge length first
Improvement Three: Do not need so many if else, the symbol can be judged by ASCII code stack<character> stack = new stack<character> (); char[] ch = S.tochararray (); for (int i = 0; i < ch.length; i++) {if (ch[i] = = ' (') | | (Ch[i] = = ' [') | | (Ch[i] = = ' {')) Stack.push (Ch[i]), else {if (ch[i] = = ') ') {if (Stack.isempty ()) return False;else if (Stack.pop ()! = ' (') RET Urn false;} if (ch[i] = = '] ') {if (Stack.isempty ()) Return false;if (Stack.pop ()! = ' [') return false;} if (ch[i] = = '} ') {if (Stack.isempty ()) Return false;if (Stack.pop ()! = ' {') return false;}}} if (!stack.isempty ()) return False;elsereturn true;} }
Valid parentheses (Stack)