摘要:循环每个元素放入堆栈或比较是否和栈顶元素成对。循环结束后,若未抛出,且堆栈为空,说明所有都已一一对应。
Problem
Given a string containing just the characters "(", ")", "{", "}", "[" and "]", determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
Note建立堆栈stack。循环每个元素放入堆栈或比较是否和栈顶元素成对。
循环结束后,若未抛出false,且堆栈为空,说明所有parenthese都已一一对应。
public class Solution { public boolean isValid(String s) { Mapif-else branchesmap = new HashMap<>(); map.put("(", ")"); map.put("[", "]"); map.put("{", "}"); Stack stack = new Stack<>(); for (int i = 0; i < s.length(); i++) { Character ch = s.charAt(i); switch (ch) { case "{": case "[": case "(": stack.push(ch); break; case ")": case "}": case "]": if (stack.isEmpty() || ch != map.get(stack.pop())) return false; } } return stack.isEmpty(); } }
public class Solution { /** * @param s: A string * @return: whether the string is a valid parentheses */ public boolean isValidParentheses(String s) { char[] str = s.toCharArray(); if (str.length % 2 != 0) return false; Stackstack = new Stack<>(); for (char ch: str) { if (ch == "(" || ch == "[" || ch == "{") { stack.push(ch); } else { if (stack.isEmpty()) { return false; } else { char top = stack.pop(); if ((ch == ")" && top != "(") || (ch == "]" && top != "[") || (ch == "}" && top != "{")) { return false; } } } } return stack.isEmpty(); } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/64936.html
摘要:在问题中,我们可以用来检验括号对,也可以通过来检验。遇到就加一,遇到就减一。找到一对括号就在最终结果上加。我们用来表示当前位置的最长括号。括号之间的关系有两种,包含和相离。 Longest Valid Parentheses Given a string containing just the characters ( and ), find the length of the lon...
摘要:假设是从下标开始到字符串结尾最长括号对长度,是字符串下标为的括号。如果所有符号都是,说明是有效的。 Longest Valid Parentheses Given a string containing just the characters ( and ), find the length of the longest valid (well-formed) parentheses...
Problem Given a string containing just the characters ( and ), find the length of the longest valid (well-formed) parentheses substring. Example 1: Input: (()Output: 2Explanation: The longest valid pa...
摘要:如栈中是,来一个变成,再来一个,变成。注意栈在或者操作之前要验证非空,否则会抛出。代码最后要判断栈的大小,如果循环结束后栈内还有元素,说明也是无效的代码 Valid Parentheses Given a string containing just the characters (, ), {, }, [ and ], determine if the input string is...
摘要:题目要求原题地址一个括号序列,求出其中成对括号的最大长度思路一使用堆栈这题可以参考我的另一篇博客这篇博客讲解了如何用堆栈判断括号序列是否可以成对。我们可以将堆栈的思路延续到这里。在这里需要先遍历一遍字符串,再遍历一下非空的堆栈。 题目要求 原题地址:https://leetcode.com/problems... Given a string containing just the c...
阅读 1609·2021-10-25 09:46
阅读 3160·2021-10-08 10:04
阅读 2325·2021-09-06 15:00
阅读 2751·2021-08-19 10:57
阅读 2052·2019-08-30 11:03
阅读 947·2019-08-30 11:00
阅读 2345·2019-08-26 17:10
阅读 3521·2019-08-26 13:36