判斷一個字符串中的括號是否成對出現
該題的核心思路在於使用棧。面試
該方法雖然不是最優解 可是思路仍是比較清晰的微信
/** * @author rale * 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 Solution1 { public boolean isValid(String s) { char[] list = s.toCharArray(); Stack<Character> stack = new Stack<Character>(); for(char temp : list){ if(temp=='(' || temp=='[' || temp=='{'){ stack.push(temp); } if(temp=='}' && (stack.isEmpty()||stack.pop()!='{')){ return false; } if(temp==')' && (stack.isEmpty()||stack.pop()!='(')){ return false; } if(temp==']'&& (stack.isEmpty()||stack.pop()!='[')){ return false; } } if(!stack.isEmpty()){ return false; } return true; } }
想要了解更多開發技術,面試教程以及互聯網公司內推,歡迎關注個人微信公衆號!將會不按期的發放福利哦~spa