20. Valid Parentheses括号匹配


20 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.

自己代码:

class Solution {
public:
    bool isValid(string s) {
        stack<char> parent;
        for(char c:s){
            if(c ==‘[‘||c == ‘(‘ || c == ‘{‘) parent.push(c);  //左括号进栈
            else if(parent.empty()) return false;
            else{                                              //有右括号且与栈顶匹配,则栈顶元素出栈
                if(c ==‘]‘ && parent.top() == ‘[‘) parent.pop();
                else if(c ==‘}‘ && parent.top() == ‘{‘) parent.pop();
                else if(c ==‘)‘ && parent.top() == ‘(‘) parent.pop();
                else return false;
            }
        }
        if(parent.empty()) return true;
        else return false;
    }

};

巧妙的方法,discussion区发现:

遇到左括号,则使对应右括号进栈,例如:遇到“{”,进栈“}”。遇到“[”,进栈“]”。遇到“(”,进栈“)”。

非右括号,则看它是否与栈顶元素相等,相等即匹配。

public boolean isValid(String s) {
    Stack<Character> stack = new Stack<Character>();
    for (char c : s.toCharArray()) {
        if (c == ‘(‘)                                 //遇到左右括号,使括号进栈
            stack.push(‘)‘);
        else if (c == ‘{‘)
            stack.push(‘}‘);
        else if (c == ‘[‘)
            stack.push(‘]‘);
        else if (stack.isEmpty() || stack.pop() != c)  //遇到非右括号,若栈空,返回false。否则弹出栈顶元素,看其是否与当前元素相等,否则错误
            return false;
    }
    return stack.isEmpty();
}

用switch语句写:

 bool isValid(string s) {
        stack<char> paren;
        for (char& c : s) {
            switch (c) {
                case ‘(‘:
                case ‘{‘:
                case ‘[‘: paren.push(c); break;
                case ‘)‘: if (paren.empty() || paren.top()!=‘(‘) return false; else paren.pop(); break;
                case ‘}‘: if (paren.empty() || paren.top()!=‘{‘) return false; else paren.pop(); break;
                case ‘]‘: if (paren.empty() || paren.top()!=‘[‘) return false; else paren.pop(); break;
                default: ; // pass
            }
        }
        return paren.empty() ;
    }
时间: 2024-08-27 08:30:26

20. Valid Parentheses括号匹配的相关文章

LeetCode 20 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 "([)]&

20. 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 "([)]"

20. Valid Parentheses - 括号匹配验证

Description: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. Example: The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]&quo

leetcode 20 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 "([)]"

Valid Parentheses(括号匹配)

解决思路: 1. 栈 2.使用Map,判断是否 public boolean isValid(String s) { Stack<Character> parens = new Stack<>(); Map<Character, Character> parenMap = new HashMap<>(); parenMap.put('(', ')'); parenMap.put('[', ']'); parenMap.put('{', '}'); for (

[LeetCode]20 Valid Parentheses 有效的括号

[LeetCode]20 Valid Parentheses 有效的括号 Description Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brac

leetCode 20. Valid Parentheses 字符串

20. 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 "(]&quo

LeetCode解题笔记 - 20. Valid Parentheses

这星期听别人说在做LeetCode,让他分享一题来看看.试了感觉挺有意思,可以培养自己的思路,还能方便的查看优秀的解决方案.准备自己也开始. 解决方案通常有多种多样,我觉得把自己的解决思路记录下来,阶段性查看,一定能对自己有帮助. 这是我做的第一题,所以记录也从这题开始,之后尽力以简短的说明,描述出思路,方便以后能回顾到简介明了的记录. 20. Valid Parentheses Given a string containing just the characters '(', ')', '{

刷题20. Valid Parentheses

一.题目说明 这个题目是20. Valid Parentheses,简单来说就是括号匹配.在学数据结构的时候,用栈可以解决.题目难度是Medium. 二.我的解答 栈涉及的内容不多,push.pop.top,. 我总共提交了3次: 第1次:Runtime Error,错误原因在于pop的时候,未判断栈是否为空. 第2次:Wrong Answer,这个是"眼大"疏忽导致的,我写的时候只考虑了()[]未考虑{}. 第3次:终于正确了,性能还可以: Runtime: 0 ms, faster