GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — [LeetCode] 20. Valid Parentheses · Issue #20 · grandyang/leetcode Open Description
Given a string An input string is valid if:
Example 1: Example 2: Example 3: Constraints:
这道题让我们验证输入的字符串是否为括号字符串,包括大括号,中括号和小括号。这里需要用一个栈,开始遍历输入字符串,如果当前字符为左半边括号时,则将其压入栈中,如果遇到右半边括号时,若此时栈为空,则直接返回 false,如不为空,则取出栈顶元素,若为对应的左半边括号,则继续循环,反之返回 false,代码如下: 解法一: 再来看一种写的更加简洁的方法,这里用个小 trick,之前是当遇到左括号时,把左括号压入栈,这样在出栈检测的时候,得判断当前遇到的右括号是哪种括号,是否跟栈顶的左括号匹配。而假如在压入栈的时候,我们直接将左括号对应的右括号压入栈,则在出栈检测的时候,就直接可以比较是否和栈顶元素相等了,因为都是右括号,这样写起来能相对简单一点,但是整体的思路还是相同的,参见代码如下: 解法二: Github 同步地址: 类似题目: Different Ways to Add Parentheses Check If Word Is Valid After Substitutions Check if a Parentheses String Can Be Valid Move Pieces to Obtain a String 参考资料: https://leetcode.com/problems/valid-parentheses/ https://leetcode.com/problems/valid-parentheses/discuss/9178/Short-java-solution LeetCode All in One 题目讲解汇总(持续更新中...) (欢迎加入博主的知识星球,博主将及时答疑解惑,并分享刷题经验与总结,快快加入吧~) 微信打赏 Venmo 打赏 ActivityMetadataMetadataAssigneesLabelsNo labels TypeProjectsMilestoneRelationshipsDevelopmentIssue actions |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |