LeetCode-Easy020-Valid-Parentheses

53次阅读

共计 602 个字符,预计需要花费 2 分钟才能阅读完成。

Easy 020 Valid Parentheses

Description:

“()”“[]” “{}” 三种括号匹配问题,判断参数字符串是否满足匹配要求
如:“({[]})”true“[{})”false
Note: 空串为 true

My Solution:

    • 括号匹配问题是栈的典型应用,遇到左括号,入栈,遇到右括号,看栈顶是否是相应的左括号,若不是,则 false
    • 时间复杂度 O(n)
    • 代码如下:
    •     public boolean isValid(String s) {if(s.length()==0){return true;}
           Stack<Character> stack = new Stack<>();
           for(char c:s.toCharArray()){if(c == '(' || c == '{' || c == '['){stack.push(c);
               }else if(stack.size()==0){return false;}
               else if(c == ')' && stack.peek() == '('){stack.pop();
               }else if(c == ']' && stack.peek() == '['){stack.pop();
               }else if(c == '}' && stack.peek() == '{'){stack.pop();
               }else
                   return false;
           }
           if(stack.size() == 0){return true;}
           return false;
       }

Fast Solution:

正文完
 0