判断一个字符串中的括号是否成对出现
该题的核心思路在于使用栈。面试
该方法虽然不是最优解 可是思路仍是比较清晰的微信
/** * @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