• Lintcode423-Valid Parentheses-Easy


    思路:

    数据结构:stack。遍历整个字符串,如果遇到左向括号( [ { 则入栈。如果遇到右向括号时,先检查栈是否为空,为空说明左右向括号数目不一致,返回false;不为空则弹出栈顶元素查看是否和右向括号匹配。遍历完,要return stack.isEmpty(); 确保栈内没有剩余。

    代码:

    public class Solution {
        /**
         * @param s: A string
         * @return: whether the string is a valid parentheses
         */
        public boolean isValidParentheses(String s) {
            Stack<Character> st = new Stack<Character>();
            
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (c == '(' || c == '[' || c == '{') {
                    st.push(c);
                }
                if (c == ')' || c == ']' || c == '}') {
                    if (st.isEmpty()) {
                        return false;
                    }
                    char popChar = st.pop();
                    if ( c == ')' && popChar != ')') {
                        return false;
                    } 
                    if ( c == ']' && popChar != ']') {
                        return false;
                    }
                    if ( c == '}' && popChar != '}' ) {
                        return false;
                    }
                }
            }
        return st.isEmpty();
        }
    }

    代码风格优化:String遍历每一个char(line 9) ; 用if-else分支更准确(line 10, 12)

     1 public class Solution {
     2     /**
     3      * @param s: A string
     4      * @return: whether the string is a valid parentheses
     5      */
     6     public boolean isValidParentheses(String s) {
     7         Stack<Character> st = new Stack<Character>();
     8         
     9         for (Character c : s.toCharArray()) {
    10             if (c == '(' || c == '[' || c == '{') {
    11                 st.push(c);
    12             } else {
    13                 if (st.isEmpty()) {
    14                     return false;
    15                 }
    16                 char popChar = st.pop();
    17                 if ( c == ')' && popChar != '(') {
    18                     return false;
    19                 } 
    20                 if ( c == ']' && popChar != '[') {
    21                     return false;
    22                 }
    23                 if ( c == '}' && popChar != '{') {
    24                     return false;
    25                 }
    26             }
    27         }
    28     return st.isEmpty();
    29     }
    30 }
  • 相关阅读:
    Java并发
    JS的强制类型转换
    JS的原生函数
    JS的类型和值
    解决Oracle临时表空间占满的问题
    nginx location匹配规则
    java.util.ConcurrentModificationException 解决办法
    SQL优化三板斧:精简之道、驱动为王、集合为本
    一次非典型SQL优化:如何通过业务逻辑优化另辟蹊径?
    一次耐人寻味的SQL优化:除了SQL改写,还要考虑什么?
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/10665079.html
Copyright © 2020-2023  润新知