内容简介: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 brackets.
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 brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1: Input: "()" Output: true Example 2: Input: "()[]{}" Output: true Example 3: Input: "(]" Output: false Example 4: Input: "([)]" Output: false Example 5: Input: "{[]}" Output: true
难度:easy
题目:
给定仅包含字符'(', ')', '{', '}', '[' 和 ']'的字符串, 判定这个字符串是否有效。
输入字符串是否有效:
开括号必需与同类型括号关闭。
开括号必需要以正确的顺序关闭。
注意 空字符串被认为是有效的字符串。
思路:stack
Runtime: 5 ms, faster than 74.68% of Java online submissions for Valid Parentheses.
Memory Usage: 26.3 MB, less than 52.20% of Java online submissions for Valid Parentheses.
class Solution { public boolean isValid(String s) { // stack Stack<Character> stack = new Stack<>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '(') { stack.push(')'); } else if (c == '{') { stack.push('}'); } else if (c == '[') { stack.push(']'); } else { if (stack.isEmpty() || stack.pop() != c) { return false; } } } return stack.isEmpty(); } }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 20. Valid Parentheses
- LeetCode 20. Valid Parentheses
- [swift] LeetCode 20. Valid Parentheses
- LeetCode集锦(六) - 第20题 Valid Parentheses
- Leetcode基础刷题之PHP解析(20. Valid Parentheses)
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
深入浅出SQL(中文版)
贝里 编 / O‘Reilly Taiwan公司 / 东南大学 / 2009-6 / 98.00元
你将从《深入浅出SQL(中文版)》学到什么?在如今的世界,数据就是力量,但是成功的真正秘诀却是管理你的数据的力量。《深入浅出SQL(中文版)》带你进入SQL语言的心脏地带,从使用INSERT和SELECT这些基本的查询语法到使用子查询(subquery)、连接(join)和事务(transaction)这样的核心技术来操作数据库。到读完《深入浅出SQL(中文版)》之时,你将不仅能够理解高效数据库设......一起来看看 《深入浅出SQL(中文版)》 这本书的介绍吧!