给定一个只包括 ‘(‘,’)’,’{‘,’}’,’[‘,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。

左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

示例 1:

输入: “()”

输出: true

示例 2:

输入: “()[]{}”

输出: true

示例 3:

输入: “(]”

输出: false

示例 4:

输入: “([)]”

输出: false

示例 5:

输入: “{[]}”

输出: true

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/valid-parentheses

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  1. class Solution {
  2. public boolean isValid(String s) {
  3. if (s == null || s.length() % 2 != 0) return false;
  4. //if (s.length() == 0) return true;
  5. char[] cs = s.toCharArray();
  6. Deque<Character> stack = new ArrayDeque<>();
  7. for (char c : cs) {
  8. if (c == '(' || c == '{' || c == '['){
  9. stack.push(c);
  10. }else {
  11. Character last = stack.poll();
  12. if (last == null) return false;
  13. if (c == ')') {
  14. if (last != '(') return false;
  15. } else{
  16. if((c - 2) != last) return false;
  17. }
  18. }
  19. }
  20. return stack.size() == 0;
  21. }
  22. }

减少栈储存耗时

  1. class Solution {
  2. public boolean isValid(String s) {
  3. char[] res = new char[s.length() + 1];
  4. int index = 1;
  5. for (char tmp : s.toCharArray()) {
  6. if (tmp == '(' || tmp == '{' || tmp == '[') {
  7. res[index++] = tmp;
  8. } else {
  9. index--;
  10. if (tmp == ')' && res[index] != '(') {
  11. return false;
  12. }
  13. if (tmp == '}' && res[index] != '{') {
  14. return false;
  15. }
  16. if (tmp == ']' && res[index] != '[') {
  17. return false;
  18. }
  19. }
  20. }
  21. return index == 1;
  22. }
  23. }