leetCode 20.Valid Parentheses (有效的括号) 解题思路和方法

原创 2015年07月06日 17:21:26
Valid Parentheses 
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.


思路:题目总体上比较明确,是对括号是否有效做判断,算法上是用栈来实现,单边入栈,配对之后出栈,最后判断栈是否为空,不为空说明最后没有配对完成,返回false.

具体代码如下:

public class Solution {
    public boolean isValid(String s) {
        Stack<Character> st = new Stack<Character>();
        char[] ch = s.toCharArray();
        int len = ch.length;
        //如果长度为奇数,肯定无效
        if((len & 1) != 0){
            return false;
        }
        
        for(int i = 0; i < len; i++){
            if(st.isEmpty()){//栈为空,直接入栈
                st.push(ch[i]);
            }else{//不为空则讨论栈顶元素是否与ch[i]配对。配对也出栈
                if(isMatch(st.peek(),ch[i])){//是否配对
                    st.pop();//栈顶元素出栈
                }else{
                    st.push(ch[i]);//不配对入栈
                }
            }
        }
        return st.isEmpty();
    }
    //a为栈顶元素,b为字符串最前元素
    public static boolean isMatch(char a, char b){
        switch(a){
            case '(': if(b == ')') return true; else return false;
            case '{': if(b == '}') return true; else return false;
            case '[': if(b == ']') return true; else return false;
            default : return false;
        }
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

leetCode 32.Longest Valid Parentheses (有效的最大括号) 解题思路和方法

Longest Valid Parentheses  Given a string containing just the characters '(' and ')', find the ...

leetCode 22.Generate Parentheses (生成括号) 解题思路和方法

Generate Parentheses  Given n pairs of parentheses, write a function to generate all combinatio...

leetCode 36.Valid Sudoku(有效的数独) 解题思路和方法

Valid Sudoku Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sud...

LeetCode | 32. Longest Valid Parentheses——最长有效括号匹配长度

Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (wel...

LeetCode--Longest Valid Parentheses(最长有效的括号)

转自:http://www.cnblogs.com/lichen782/archive/2013/07/06/leetcode_Longest_Valid_Parentheses.html

Leetcode刷题记——32. Longest Valid Parentheses(最长有效括号)

一、题目叙述: Given a string containing just the characters '(' and ')'...

Longest Valid Parentheses(最长有效括号串)

Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (wel...

Longest Valid Parentheses (求最长有效匹配括号子串的长度)

题目描述: Given a string containing just the characters'(' and')', find the length of the longest...
  • LGCSSX
  • LGCSSX
  • 2013-06-24 16:56
  • 1449

20. Valid Parentheses (括号匹配)

Given a string containing just the characters '(', ')', '{', '}', '[' and &...

20.Valid Parentheses&合法括号序列判断

Given a string containing just the characters '(', ')', '{', '}', '[' and &...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)