给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。class Solution {
public boolean isValid(String s) { if(s.length()==0){ return true; } if(s.length()==1){ return false; } Stack<Character> stack=new Stack<>(); int i=0; stack.push(s.charAt(i)); i++; while(i!=s.length()){ char tmp = s.charAt(i); if(!stack.empty()){ char peek = stack.peek(); if((tmp == ')'&&peek=='(')||(tmp==']'&&peek=='[')||(tmp=='}'&&peek=='{')){ stack.pop(); i++; continue; } } stack.push(tmp); i++; } return stack.empty(); } }
思路:最终以栈内元素是否为空进行判断,可以避免考虑遍历过程中的多种情况。