日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

[LeetCode]--20. Valid Parentheses

發(fā)布時(shí)間:2023/12/4 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [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)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。