棧問(wèn)題通常和對(duì)稱聯(lián)系起來(lái),一個(gè)出現(xiàn),必須和另一個(gè)出現(xiàn)才合法,例如,出現(xiàn)“(”,就要出現(xiàn)“)”才合法,當(dāng)遇到對(duì)稱的問(wèn)題時(shí),可以考慮是不是棧問(wèn)題
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.
給定一個(gè)只包含字符’(’,’)’,’{‘,’}’,’[‘和’]’的字符串,確定輸入字符串是否有效。
括號(hào)必須以正確的順序關(guān)閉,“()”和“()[] {}”都有效,但“(]”和“([]]”不是。
代碼:
public class Solution { public boolean isValid(String s) { Stack<Integer> stack = new Stack<Integer>(); String rule = "()[]{}"; for(int i=0; i<s.length(); i++){ int index = rule.indexOf(s.substring(i, i+1)); if(index % 2 == 1){ if(stack.isEmpty() || stack.pop() != index-1){ return false; } }else{ stack.push(index); } } return stack.isEmpty(); }}這里的思路是: “(”必須和“)”對(duì)應(yīng),因此定義一個(gè)rule = “(){}[]”,可見左邊的下標(biāo)是偶數(shù),右邊的下標(biāo)是基數(shù)
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注