首页 > 其他 > 详细

lintcode 容易题:Valid Parentheses 有效的括号序列

时间:2015-10-17 20:42:05      阅读:172      评论:0      收藏:0      [点我收藏+]

题目:

给定一个字符串所表示的括号序列,包含以下字符: ‘(‘, ‘)‘‘{‘‘}‘‘[‘ and‘]‘, 判定是否是有效的括号序列。

样例

括号必须依照 "()" 顺序表示, "()[]{}" 是有效的括号,但 "([)]"则是无效的括号。

挑战

O(n)的时间,n为括号的个数

解题:

数据结构上面讲过的,碰到"[","(","{"入栈,碰到"]"检测栈顶是不是"[",是出栈,不是返回false,对")","}"同理了。开始我用LinkedList实现栈,没有搞好,然后网上看到java有Stack的。import.util.Stack,然后想着写简单点,有错了一路。。。

Java程序:

技术分享
public class Solution {
    /**
     * @param s A string
     * @return whether the string is a valid parentheses
     */
    public boolean isValidParentheses(String s) {
        // Write your code here
        Stack<Character> stack = new Stack<Character>();
        int slen = s.length();
        char elm ;
        for( int i = 0;i< slen ;i++){
            elm = s.charAt(i);
            if(elm==‘[‘ || elm==‘(‘ || elm ==‘{‘)
                stack.push(elm);
            else if(elm ==‘]‘){
                if(stack.empty())
                    return false;
                char top = stack.peek();
                if(top== ‘[‘)
                    stack.pop();
                else
                    return false;
                }else if(elm ==‘)‘){
                if(stack.empty())
                    return false;
                char top = stack.peek();
                if(top== ‘(‘)
                    stack.pop();
                else
                    return false;
                }else if(elm ==‘}‘){
                if(stack.empty())
                    return false;
                char top = stack.peek();
                if(top== ‘{‘)
                    stack.pop();
                else
                    return false;
                }
        }
    
        if(stack.empty()==true)
                return true;
         return false;
        
    }
}
View Code

总耗时: 9492 ms

python程序,用list实现stack,pop是可以直接出栈,append入栈

Python程序:

技术分享
class Solution:
    # @param {string} s A string
    # @return {boolean} whether the string is a valid parentheses
    def isValidParentheses(self, s):
        # Write your code here
        stack = [] 
        slen = len(s) 
        for elm in s:
            if elm==( or elm == [ or elm == {:
                stack.append(elm)
            elif elm==) or elm == ] or elm == }:
                if len(stack)==0:
                    return False
                top = stack.pop()
                if top == ( and elm== ):
                    continue
                elif top == [ and elm ==]:
                    continue
                elif top == { and elm == }:
                    continue
                else:
                    return False
        if len(stack)==0:
            return True
        else:
            return False 
View Code

总耗时: 409 ms

lintcode 容易题:Valid Parentheses 有效的括号序列

原文:http://www.cnblogs.com/theskulls/p/4888113.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!