内容简介: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)
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
创投之巅——中国创投精彩案例
投资界网站 / 人民邮电出版社 / 2018-11 / 69.00
中国的科技产业发展,与创投行业密不可分。在过去的几十年间,资本与科技的结合,缔造了众多创业“神话”。回顾这些科技巨头背后的资本路径,可以给如今的国内创业者很多有益的启发。 本书从风险投资回报率、投资周期、利润水平、未来趋势等多个维度,筛选出了我国过去几十年中最具代表性的创业投资案例,对其投资过程和企业成长过程进行复盘和解读,使读者可以清晰地看到优秀创业公司的价值与卓越投资人的投资逻辑。一起来看看 《创投之巅——中国创投精彩案例》 这本书的介绍吧!