`
king_tt
  • 浏览: 2083590 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

【leetcode】Valid Parentheses

 
阅读更多

Question :

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.

Anwser 1 : Stack

class Solution {
public:
    bool isValid(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        stack<char> st;
        for(int i = 0; i < s.size(); i++)
        {
            if(s[i] == '(' || s[i] == '{' || s[i] == '['){
                st.push(s[i]);
            }
               
            if(s[i] == ')')
            {
                if(st.empty() || st.top() != '(')
                   return false;
                st.pop();
            }
            if(s[i] == '}')
            {
                if(st.empty() || st.top() != '{')
                   return false;
                st.pop();
            }
            if(s[i] == ']')
            {
                if(st.empty() || st.top() != '[')
                   return false;
                st.pop();
            }            
        }
        if(st.empty() == 0)
           return false;
           
        return true;
    }
};


Anwser 2 :

class Solution {
public:
    bool isValid(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        stack<char> st;
        for (int i = 0; i < s.size(); i++) {
            char c = s[i];
            if (isLeft(c)) {    // push
                st.push(c);
            } else {
                if (st.empty()) {
                    return false;
                }
                char d = st.top();      // pop
                st.pop();
                if (!match(d,  c)) {
                    return false;
                }
            }
        }
 
        if (st.empty()) {
            return true;
        }
        else {
            return false;
        }
    }
 
    bool isLeft(char c) {
        return c == '{' || c == '[' || c == '(';
    }
    
    bool match(char c, char d) {
        return (c == '(' && d == ')') || (c == '[' && d == ']') || (c == '{' && d == '}');
    }
};


分享到:
评论

相关推荐

    leetcode2-valid_parentheses:代码挑战:有效括号

    leetcode 2 有效括号 给定一个只包含字符'(' , ')' , '{' , '}' , '['和']'的字符串,确定输入字符串是否有效。 输入字符串在以下情况下有效: * 左括号必须由相同类型的括号封闭。 * 左括号必须以正确的顺序关闭。 ...

    程序员面试宝典LeetCode刷题手册

    第四章 Leetcode 题解 ...20. Valid Parentheses 21. Merge Two Sorted Lists 22. Generate Parentheses 23. Merge k Sorted Lists 24. Swap Nodes in Pairs 25. Reverse Nodes in k-Group 26. Remove Dupli

    颜色分类leetcode-leetcode-[removed]我对Leetcode问题的解决方案

    颜色分类leetcode My Leetcode Problems Solutions Using javascript(ES6) 1 Two Sum 两数之和 5 Longest Palindromic Substring 最长回文子串 7 Reverse Integer 整数反转 9 Palindrome Number 回文数 11 Container...

    LeetCode最全代码

    # [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License]...

    javalruleetcode-LeetCode::lollipop:个人LeetCode习题解答仓库-多语言

    java lru leetcode :ice_cream: LeetCode ...Parentheses 26 Remove Duplicates from Sorted Array 48 Rotate Image 53 Maximum Subarray 55 Jump Game 56 Merge Intervals 64 Minimum Path Sum 73

    Leetcode扑克-leetcode:Leetcode算法实践

    Parentheses 有效的括号 Stack / 栈 用栈实现配对 Daily Challenge 2020/08/14 28 Implement strStr() 实现 strStr() String / 字符串 循环遍历即可 algorithm-pattern: quick start 43 Multiply S

    leetcode中国-leetcode:leetcode刷题

    Parentheses 用栈判断括号匹配 Regular Expression Matching 递归匹配 wildcard matching 动态规划 longest common prefix , 简单 valid number, hard, 用有限自动机 integer to roman ,easy , 模拟 roman to ...

    lrucacheleetcode-leetcode:leetcode

    Valid Parentheses 21. Merge Two Sorted Lists 22. Generate Parentheses 25. Reverse Nodes in k-Group 26. Remove Duplicates from Sorted Array 27. Remove Element 28. Implement strStr() 3

    LeetCode字符串换行-Solve_Leetcode:Solve_Leetcode

    LeetCode字符串换行 Solve_Leetcode 复习的过程,来刷刷题,坚持坚持坚持! 逆波兰表达式 题目如下: 使用了 class Stack A more complete and consistent ...Valid Parentheses 题目如下: Stack泛型

    leetcode题库-LeetCode:力码

    leetcode题库 LeetCode 题解合集 本仓库展示了LeetCode题库中部分题目的解法(持续更新),所有代码均采用C++编写并配有输入输出样例 代码清单如下: 序号 题目 程序源码 ...Parentheses.cpp 22 括号生成 G

    leetcode怎么改密码-Code:学会学习

    leetcode怎么改密码 Code leetcode easy 测试一下本地的... emmmmm之前修改了一下,现在用ssh提交 应该不用输入密码了吧 ~~emmmmm 先在这里立个flag!!...Valid Parentheses :cross_mark:暴力解法(未通过)

    leetcode530-algorithm:算法

    leetcode 530 ** LeetCode 题目更新 ** 用来记录业余时间所做的算法题目,保持对于数据结构的熟悉。 ** ...Valid Parentheses 022 Generate Parentheses 028 Implement strStr() 031 Next Permutat

    leetcode双人赛-LeetCode:力扣笔记

    leetcode双人赛LeetCode 编号 题目 难度 题型 备注 Two Sum 简单 Add Two Numbers 中等 链结串列 重要 Longest Substring Without Repeating Characters 中等 字串 重要 Median of Two Sorted Arrays 困难 数学 ...

    gasstationleetcode-leetcode_java:为求职做准备。Leetcode的java版本

    加油站 leetcode leetcode_java prepare for jobhunting. java version of Leetcode. easy 55 about takes 5 days medium 112 about takes 20 days hard ...Leetcode ...1.Valid Parentheses 2.Maximum

    javalruleetcode-learn-algorithms::laptop:Java实现的各种算法题解

    java lru leetcode ...Parentheses](./leetcode/动态规划-Longest Valid Parentheses.java) [动态规划-Maximum Length of Repeated Subarray](./leetcode/动态规划-Maximum Length of Repeated Subar

    leetcode跳跃-LeetCode:力扣刷题70道!

    leetcode 跳跃 LeetCode 力扣刷题70道! 数组 Array 力扣 485 最大连续1的个数 | Max Consecutive ...Parentheses 力扣 496 下一个更大的元素 | Next Greater Element I 力扣 232 用栈实现队列 | Implement

    javalruleetcode-leetcode-java:力码笔记

    Parentheses 26.Remove Duplicates from Sorted Array 53.Maximum Subarray 70.Climbing Stairs 121.Best Time to Buy and Sell Stock 122.Best Time to Buy and Sell Stock II 123.Best Time to Buy and Sell Stock...

    leetcode-go:我使用Golang解决LeetCode问题的方法

    goMy solution to LeetCode problems using GolangProblems 题库Array 数组NoTitle题名DifficultyStatus11Container With Most Water盛最多水的容器MediumSolved26Remove Duplicates from Sorted Array删除有序数组...

    leetcode答案-LeetCode-Trip:LeetCode刷题代码,大佬勿入

    Parentheses] [21. Merge Two Sorted Lists] [53. Maximum Subarray] [70. Climbing Stairs] [101. Symmetric Tree] [104. Maximum Depth of Binary Tree] [121. Best Time to Buy and Sell Stock] [167. Two Sum II...

    典型相关分析matlab实现代码-leetcode-algorithm:leetcode刷起来!

    ValidParentheses HashMap 还有 Stack 栈 最佳实践,Deque = Stack public static boolean isValid(String s) { if(s.length() == 0 || s == null || s.length() %2 != 0) return false; Deque deque = new ...

Global site tag (gtag.js) - Google Analytics