欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

【LeetCode从零单排】No20.ValidParentheses

发布时间:2025/4/5 编程问答 21 豆豆
生活随笔 收集整理的这篇文章主要介绍了 【LeetCode从零单排】No20.ValidParentheses 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

题目

     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.

     这道题比较经典了,就是有点像编译器判断代码符号是否符合规则,是堆栈的一个简单应用。当遇到"{","[","("的时候入栈,如果遇到这些符号的另一半,则取栈顶比较,如果是一对就继续,不然返回false。

代码

public class Solution {public boolean isValid(String s) {if(s.length()==0) return true;int len=s.length();char[] symbolFirst={'(','{','['};char[] symbolSecond={')','}',']'};char strChar[]=s.toCharArray(); Stack sym=new Stack();for(int i=0;i<len;i++){for(int j=0;j<symbolFirst.length;j++){if(strChar[i]==symbolFirst[j]){if(len==1){return false;}sym.push(strChar[i]);} }for(int k=0;k<symbolSecond.length;k++){if(strChar[i]==symbolSecond[k]){if(sym.isEmpty()){return false;}else{if(!sym.peek().equals(symbolFirst[k])){return false; }else{sym.pop();}}}}}if(sym.isEmpty()){return true;}else{return false;} } }
代码下载:https://github.com/jimenbian/GarvinLeetCode


/********************************

* 本文来自博客  “李博Garvin“

* 转载请标明出处:http://blog.csdn.net/buptgshengod

******************************************/


总结

以上是生活随笔为你收集整理的【LeetCode从零单排】No20.ValidParentheses的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。