【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.
? ? ?這道題比較經(jīng)典了,就是有點(diǎn)像編譯器判斷代碼符號(hào)是否符合規(guī)則,是堆棧的一個(gè)簡(jiǎn)單應(yīng)用。當(dāng)遇到"{","[","("的時(shí)候入棧,如果遇到這些符號(hào)的另一半,則取棧頂比較,如果是一對(duì)就繼續(xù),不然返回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
/********************************
* 本文來(lái)自博客 ?“李博Garvin“
* 轉(zhuǎn)載請(qǐng)標(biāo)明出處:http://blog.csdn.net/buptgshengod
******************************************/
總結(jié)
以上是生活随笔為你收集整理的【LeetCode从零单排】No20.ValidParentheses的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【LeetCode从零单排】No14.L
- 下一篇: 【LeetCode从零单排】No19.R