lintcode: 有效的括号序列

题目:

给定一个字符串所表示的括号序列,包含以下字符: '(', ')''{''}''[' 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

原文地址:https://www.cnblogs.com/theskulls/p/4888113.html