[LeetCode]--20. Valid Parentheses
生活随笔
收集整理的這篇文章主要介紹了
[LeetCode]--20. Valid Parentheses
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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.
public boolean isValid(String s) {if (s.length() % 2 != 0)return false;char[] characters = new char[s.length()];int index = 0, i;for (i = 0; i < s.length(); i++) {if (s.charAt(i) == '(')characters[index++] = s.charAt(i);if (s.charAt(i) == '[')characters[index++] = s.charAt(i);if (s.charAt(i) == '{') {characters[index++] = s.charAt(i);System.out.println(index);}if (s.charAt(i) == ')') {if (--index < 0 || characters[index] != '(')break;}if (s.charAt(i) == ']') {if (--index < 0 || characters[index] != '[')break;}if (s.charAt(i) == '}') {if (--index < 0 || characters[index] != '{')break;}}if (i == s.length() && index == 0)return true;return false;}方法通過(guò)了,不過(guò)覺(jué)得有點(diǎn)笨,暫時(shí)也沒(méi)想到好的,先就這樣啦。LeedCode也沒(méi)給我們提供詳解。
找到一個(gè)寫得比較好的程序,極力推薦大家不要看我的,看這個(gè),又感覺(jué)被甩了幾條街。
public boolean isValidParentheses(String s) {Stack<Character> stack = new Stack<Character>();for (Character c : s.toCharArray()) {if ("({[".contains(String.valueOf(c))) {stack.push(c);} else {if (!stack.isEmpty() && is_valid(stack.peek(), c)) {stack.pop();} else {return false;}}}return stack.isEmpty();}private boolean is_valid(char c1, char c2) {return (c1 == '(' && c2 == ')') || (c1 == '{' && c2 == '}')|| (c1 == '[' && c2 == ']');}用了系統(tǒng)的棧,我用的數(shù)組棧。
總結(jié)
以上是生活随笔為你收集整理的[LeetCode]--20. Valid Parentheses的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: react学习系列之states与pro
- 下一篇: CAD数据与ArcGIS数据的互转换(转