棧問題通常和對稱聯系起來,一個出現,必須和另一個出現才合法,例如,出現“(”,就要出現“)”才合法,當遇到對稱的問題時,可以考慮是不是棧問題
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 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(); }}這里的思路是: “(”必須和“)”對應,因此定義一個rule = “(){}[]”,可見左邊的下標是偶數,右邊的下標是基數
新聞熱點
疑難解答