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 }

 

转载于:https://www.cnblogs.com/Jessiezyr/p/10665079.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值