您的位置:首页 > 编程语言 > Java开发

【LeetCode刷题】有效的括号字符串Valid Parentheses(java)

2018-01-22 15:19 381 查看
题目:

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.

解答:

这个题我也没有想出来,leetcode上别人上传的代码。对于这个题该如何找思路?不管这个字符串是什么样的,如果有效,那么出现的第一个“)”、”}”、”]”左边的字符肯定与其相匹配,匹配之后将这个括号对儿扔出去,继续匹配,如果最后都能扔完,这就证明所有的括号都匹配上了,因此这个字符串就是有效的。

思路如此,该如何实现呢。下面的代码使用了栈stack。开始遍历字符串,假设当前元素是c

1)如果c是”(“、”{“、”[“,就向stack中装入相匹配的”)”、”}”、”]”;

2)如果c是”)”、”}”、”]”,则栈内元素开始pop,pop出的元素与c相同,则继续遍历;如果不同,则该字符串已经无法完全匹配,无效;

3)自己写写画画就明白啦~~~

class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: