LeetCode 20 — Valid Parentheses(C++ Java Python)

题目:http://oj.leetcode.com/problems/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.

题目翻译:

给定只包含字符'(',')','{','}','['和']'的字符串,判断输入的字符串是否有效。
括号必须以正确的顺序闭合,"()"和"()[]{}"都是有效的,但"(]" 和"([)]"是无效的。
分析:

        使用stack来实现。

C++实现:

class Solution {
public:
    bool isValid(string s) {
    	if(s.length() == 0)
    	{
    		return true;
    	}

    	stack st;
    	st.push(s[0]);

    	for(int i = 1; i < s.length(); ++i)
    	{
    		if(!st.empty() && isMatch(st.top(), s[i]))
    		{
    			st.pop();
    		}
    		else
    		{
    			st.push(s[i]);
    		}
    	}

    	if(st.empty())
    	{
    		return true;
    	}
    	else
    	{
    		return false;
    	}
    }

    bool isMatch(char s, char p)
    {
    	if((s == '(' && p == ')')
    	|| (s == '{' && p == '}')
    	|| (s == '[' && p == ']'))
    	{
    		return true;
    	}
    	else
    	{
    		return false;
    	}
    }
};

Java实现:

public class Solution {
    public boolean isValid(String s) {
        if (s.length() == 0) {
			return true;
		}

		Stack st = new Stack();
		st.push(s.charAt(0));

		for (int i = 1; i < s.length(); ++i) {
			if (!st.empty() && isMatch(st.peek(), s.charAt(i))) {
				st.pop();
			}
			else {
				st.push(s.charAt(i));
			}
		}
		
		if(st.empty()) {
			return true;
		}

		return false;
	}

	public boolean isMatch(char s, char p) {
		if ((s == '(' && p == ')') || (s == '{' && p == '}')
				|| (s == '[' && p == ']')) {
			return true;
		}

		return false;
    }
}

Python实现:

class Solution:
    # @return a boolean
    def isValid(self, s):
        if len(s) == 0:
            return True
        
        st = [s[0]]
        
        i = 1
        while i < len(s):
            if len(st) == 0:
                st.append(s[i])
            else:
                tmp = st.pop()
                if self.isMatch(tmp, s[i]):
                    pass 
                else:
                    st.append(tmp)
                    st.append(s[i])
            
            i += 1
        
        if len(st) == 0:
            return True
        
        return False
            
    def isMatch(self, s, p):
        if (s == '(' and p == ')') or \
           (s == '{' and p == '}') or \
           (s == '[' and p == ']'):
            return True
        
        return False

        感谢阅读,欢迎评论!

你可能感兴趣的:(LeetCode)