给定一个只包括 ‘(‘,’)’,’{‘,’}’,’[‘,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
示例 1:
输入:s = "()"输出:true
示例 2:
输入:s = "()[]{}"输出:true
示例 3:
输入:s = "(]"输出:false
示例 4:
输入:s = "([)]"输出:false
示例 5:
输入:s = "{[]}"输出:true
提示:
1 <= s.length <= 10s仅由括号'()[]{}'组成
我的写法:
class Solution {public boolean isValid(String s) {Stack<Character> stack = new Stack<>();HashMap<Character, Character> map = new HashMap<>();map.put('(',')');map.put('{','}');map.put('[',']');for (int i = 0; i < s.length(); i++) {char c = s.charAt(i);if (map.containsKey(c)) {stack.push(map.get(c));continue;}if (stack.isEmpty()||c!=stack.pop()){return false;}}return stack.isEmpty();}}
大神的写法:
class Solution {public boolean isValid(String s) {//由题意,s!=null, s.length>=1// if (s.length() == 0) {// return true;// }char[] stack = new char[s.length()];int head = 0;for (char c : s.toCharArray()) {switch(c) {case '(': stack[head++] = ')';break;case '[': stack[head++] = ']';break;case '{': stack[head++] = '}';break;default:if (head == 0 || stack[--head] != c) {return false;}}}return head == 0;}
