[LeetCode] 020. Valid Parentheses (Easy) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)

Github: https://github.com/illuz/leetcode


020.Valid_Parentheses (Easy)

链接

题目:https://oj.leetcode.com/problems/valid-parentheses/

代码(github):https://github.com/illuz/leetcode

题意

判断一个括号字符串是否是有效的。

分析

直接用栈模拟,很简单的。

Java 的括号匹配可以用 if 写,也可以用 HashMap<Character, Character> 存,还可以用 "(){}[]".indexOf(s.substring(i, i + 1)。 (这个讨论也可以用于 C++ 和 Python)

这里的 C++ 是用 if 匹配, Java 用 indexOf, Python 用 dict。

代码

C++:

class Solution {
public:
	bool isValid(string s) {
		stack<char> stk;
		int len = s.length();
		for (int i = 0; i < len; i++) {
			if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
				stk.push(s[i]);
			} else {
				if (stk.empty())
					return false;
				if (stk.top() == '(' && s[i] == ')')
					stk.pop();
				else if (stk.top() == '[' && s[i] == ']')
					stk.pop();
				else if (stk.top() == '{' && s[i] == '}')
					stk.pop();
				else
					return false;
			}
		}
		return stk.empty();
	}
};

Java:

public class Solution {

    public boolean isValid(String s) {
        Stack<Integer> stk = new Stack<Integer>();
        for (int i = 0; i < s.length(); ++i) {
            int pos = "(){}[]".indexOf(s.substring(i, i + 1));
            if (pos % 2 == 1) {
                if (stk.isEmpty() || stk.pop() != pos - 1)
                    return false;
            } else {
                stk.push(pos);
            }
        }
        return stk.isEmpty();
    }
}

Python:

class Solution:
    # @return a boolean
    def isValid(self, s):
        mp = {')': '(', ']': '[', '}': '{'}
        stk = []
        for ch in s:
            if ch in '([{':
                stk.append(ch)
            else:
                if not stk or mp[ch] != stk.pop():
                    return False
        return not stk
时间: 2024-10-11 22:38:35

[LeetCode] 020. Valid Parentheses (Easy) (C++/Java/Python)的相关文章

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

Problem: 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 "

LeetCode 32 Longest Valid Parentheses (C,C++,Java,Python)

Problem: Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. For "(()", the longest valid parentheses substring is "()", which has length = 2. Another exa

[LeetCode] 006. ZigZag Conversion (Easy) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 006.ZigZag_Conversion (Easy) 链接: 题目:https://oj.leetcode.com/problems/zigzag-conversion/ 代码(github):https://github.com/illuz/leetcode 题意: 把一个字符串按横写的折线排列. 分析: 直

[LeetCode] 007. Reverse Integer (Easy) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 007.Reverse_Integer (Easy) 链接: 题目:https://oj.leetcode.com/problems/Reverse-Integer/ 代码(github):https://github.com/illuz/leetcode 题意: 反转一个数. 分析: 注意读入和返回的数都是 in

[LeetCode] 009. Palindrome Number (Easy) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 009.Palindrome_Number (Easy) 链接: 题目:https://oj.leetcode.com/problems/palindrome-number/ 代码(github):https://github.com/illuz/leetcode 题意: 判断一个数是否是回文数. 分析: 按自己想

LeetCode 020 Valid Parentheses

题目描述: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 "(]&qu

[Leetcode][020] Valid Parentheses (Java)

题目在这里: https://leetcode.com/problems/valid-parentheses/ [标签]Stack; String [个人分析]这个题应该算是Stack的经典应用.先进后出 ( FILO) 的结构: 先来的左边括号跟后面的右边括号相匹配. [代码解释]创建一个栈,如果遇到的是 '{', '(', '[', 就压到栈里面去,留着跟后面遇到的后边括号匹配.如果遇到了'}', ']', ')',首先看看栈里面 是不是空,里面有没有匹配的部分. [一些心得]我在别人那儿看

LeetCode 36 Valid Sudoku (C,C++,Java,Python)

Problem: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could be partially filled, where empty cells are filled with the character '.'. A partially filled sudoku which is valid. Note: A valid Sudoku board (

[leetcode] 20. Valid Parentheses (easy)

原题链接 匹配括号 思路: 用栈,遍历过程中,匹配的成对出栈:结束后,栈空则对,栈非空则错. Runtime: 4 ms, faster than 99.94% of Java class Solution { public boolean isValid(String s) { Stack<Character> sta = new Stack<Character>(); for (int i = 0; i < s.length(); i++) { char temp = s