给定一个只包括 ‘(‘,‘)‘,‘{‘,‘}‘,‘[‘,‘]‘ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for(char c: s.toCharArray()){ if (c == ‘(‘) { stack.push(‘)‘); } else if (c == ‘[‘) { stack.push(‘]‘); } else if (c == ‘{‘) { stack.push(‘}‘); } else if (stack.isEmpty()) { return false; } else if (c != stack.pop()) { return false; } } return stack.isEmpty(); }} |
执行结果:通过
原文:https://www.cnblogs.com/keepfriend/p/14491813.html