【LeetCode算法-20】Valid Parentheses
2023-09-14 09:00:41 时间
LeetCode第20题
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
思路:
本来我的想法是不管(),[],{},都是在一起的,我一对一对的删掉,最后删空了,就符合要求
代码
class Solution {
public boolean isValid(String s) {
if(s.length()>Integer.MAX_VALUE){
return true;
}
for(int i = 0;i<3;i++){
for(int j = 0;j<s.length();j++){
s = s.replace("()","");
System.out.println(s);
s = s.replace("[]","");
System.out.println(s);
s = s.replace("{}","");
System.out.println(s);
}
}
if("".equals(s)){
return true;
}else{
return false;
}
}
}
结果
搞这么多符号,这不故意整我吗
百度了下,都说用栈,代码如下
class Solution {
public boolean isValid(String s) {
Stack<String> stack = new Stack<String>();
for (int i = 0; i < s.length(); i++) {
char candidate = s.charAt(i);
if (candidate == '{' || candidate == '[' || candidate == '(') {
stack.push(candidate + "");
} else {
if (stack.isEmpty()) {
return false;
}
if ((candidate == '}' && stack.peek().equals("{")) ||
(candidate == ']' && stack.peek().equals("[")) ||
(candidate == ')' && stack.peek().equals("("))) {
stack.pop();
} else {
return false;
}
}
}
if (stack.isEmpty()) {
return true;
} else {
return false;
}
}
}
就是利用后进先出的原理,其实跟我的思路差不多,但是性能要好很多,哈哈
相关文章
- Java实现 LeetCode 815 公交路线(创建关系+BFS)
- Java实现 LeetCode 637 二叉树的层平均值(遍历树)
- Java实现 LeetCode 999 车的可用捕获量(简单搜索)
- Java实现 LeetCode 476 数字的补数
- Java实现 LeetCode 427 建立四叉树
- Java实现 LeetCode 331 验证二叉树的前序序列化
- Java实现 LeetCode 300 最长上升子序列
- Java实现 LeetCode 233 数字 1 的个数
- Java实现 LeetCode 198 打家劫舍
- Java实现 LeetCode 137 只出现一次的数字 II(二)
- Java实现 LeetCode 101 对称二叉树
- Java实现 LeetCode 100 相同的树
- Java实现 LeetCode 77 组合
- Java实现 LeetCode 23 合并K个排序链表
- 【LeetCode算法-53】Maximum Subarray
- 【LeetCode算法-27】Remove Element
- 【LeetCode算法-20】Valid Parentheses
- 【LeetCode算法-7】Reverse Integer
- 每日一道 LeetCode (21):对称二叉树
- 【刷题】【LeetCode】总
- 【LeetCode算法-26】Remove Duplicates from Sorted Array
- 【LeetCode算法-9】Palindrome Number
- LeetCode-1144. 递减元素使数组呈锯齿状【贪心,数组】
- leetcode算法第二题python答案
- 【LeetCode-面试算法经典-Java实现】【066-Plus One(加一)】
- Leetcode 字母异位词分组(超出时间限制,但是算法可行<难受~_~>)
- [LeetCode] 382. 链表随机节点 ☆☆☆(随机算法:蓄水池抽样)
- LeetCode回溯算法的解题思路
- leetcode 66. Plus One
- 【Leetcode刷题Python】改进的算法,高效求一个数的因子
- 【Leetcode刷题Python】 LeetCode 2038. 如果相邻两个颜色均相同则删除当前颜色
- LeetCode 79. 单词搜索