【因为这有三种括号,三个之间的嵌套比较复杂,所以不能简单地使用整形int作为判断(左括号++,右括号--),例如“([)]”这要是使用int那么就会判断正确。】 算法——利用一个栈,如果是左括号则直接放入,如果是右括号,pop栈顶看是否为对应左括号,否则return false;最后检查栈是否为空。 我的代码: 1publicbooleanis...
import java.util.Stack; class Solution { public boolean isValid(String s) { Stack<Character> stack_match = new Stack<Character>(); for(int i=0;i<s.length();i++){ if(s.charAt(i)=='(' || s.charAt(i)=='[' || s.charAt(i)=='{'){ stack_match.push(s.charAt(i)); }else...
检查字符是用==,检查String是用.isEqual(),因为String是引用类型,值相等但是地址可能不等。 代码如下: 1publicbooleanisValid(String s) { 2if(s.length()==0||s.length()==1) 3returnfalse; 4 5Stack<Character> x =newStack<Character>(); 6for(inti=0;i<s.length();i++){ 7if(s.charAt(i...
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. 注意,空字符串也被视...
建议和leetcode 32. Longest Valid Parentheses 最长有效括号长度和 leetcode 678. Valid Parenthesis String 有效括号的判断 一起学习 代码如下: import java.util.ArrayList; import java.util.List; public class Solution { public boolean isValid(String s) ...
determine if the input string is valid. The brackets must close in the correct order,"()"and"()[]{}"are all valid but"(]"and"([)]"are not. 原题链接:https://oj.leetcode.com/problems/valid-parentheses/ 题目:给定一个仅包括'(',')','{','}','['和']' 的字符串,检測输入的串是...
==1 表示有A在栈底,!= 1 就表示Solution().isValid("((()[])[]") 尝试使用: 成功。 对于想刷题但是基础不够扎实的同学,推荐两本神书——一本补基础,另外一本上手算法+数据结构,助你 LeetCode 刷到飞起~
Can you solve this real interview question? Valid Parentheses - Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by th
package leetcode._20;import java.util.Stack;publicclassSolution{publicbooleanisValid(String s){Stack<Character>stack=newStack<>();for(inti=0;i<s.length();i++){charc=s.charAt(i);if(c=='('||c=='['||c=='{'){stack.push(c);}else{if(stack.isEmpty()){returnfalse;}chartop=stack...
链接:https://leetcode.com/problems/valid-parentheses/#/description 难度:Easy 题目:20. Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.The brackets must close in the correct order, "()" and ...