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.輸入一個字符串s,這個字符串是由字符'(', ')', '{', '}', '[' 和 ']'組成的。咱們須要斷定這個字符串的格式是否有效。斷定是否有效的一句就是,字符必須嚴格有序。例如"()" 和 "()[]{}"是有效的,可是"()"和"()[]{}"就是無效的。數據結構
Stack<Character> save = new Stack<Character>(); if(s.length() == 0)return true; for(char c : s.toCharArray()){ if(c == '('){ save.push(')'); }else if (c == '['){ save.push(']'); }else if (c == '{'){ save.push('}'); }else if (save.isEmpty() || c != save.pop()){ return false; } } return save.isEmpty();