美文网首页
leetcode 20 栈

leetcode 20 栈

作者: __hgb | 来源:发表于2019-06-07 11:54 被阅读0次
    20.png
        public boolean isValid(String s) {
            Stack<Character> stack = new Stack<Character>();
            for( int i = 0 ; i < s.length() ; i ++ )
                if( s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[')
                    stack.push(s.charAt(i));
                else{
    
                    if( stack.size() == 0 )
                        return false;
    
                    Character c = stack.pop();
    
                    Character match;
                    if( s.charAt(i) == ')' )
                        match = '(';
                    else if( s.charAt(i) == ']' )
                        match = '[';
                    else{
                        assert s.charAt(i) == '}';
                        match = '{';
                    }
    
                    if(c != match)
                        return false;
                }
    
            if( stack.size() != 0 )
                return false;
    
            return true;
        }
    

    相关文章

      网友评论

          本文标题:leetcode 20 栈

          本文链接:https://www.haomeiwen.com/subject/czemxctx.html