Valid Parentheses

题目


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 boolean isValid(String s) 
    {
        boolean flag = true;
        char[] ch = s.toCharArray();
        Map map = new HashMap();
        map.put('(', ')');
        map.put('[', ']');
        map.put('{', '}');
        if(s.length()%2==1)
            return flag = false;
        if(map.get(ch[1])!=null)
        {
            for(int i=0;i<s.length()/2;i++)
            {
                int k =s.length()-1-i;
                if((map.get(ch[i])==null)||(!map.get(ch[i]).equals(ch[k])))
                {
                    flag = false;
                    break;
                }
            }
        }
        else
        {
            for(int i=0;i<s.length();i+=2)
            {
                if((map.get(ch[i])==null)||(!map.get(ch[i]).equals(ch[i+1])))
                {
                    flag = false;
                    break;
                }
            }
        }
        return flag;
    }

这个代码能解决一下的问题,例如()[]{} ((())) 等问题.但是一种情况被忽略了。(()){[]}

正确代码

    public static boolean isValid(String s) 
    {
        Stack<Character> stack = new Stack<Character>();
        for(char c : s.toCharArray())
        {
            if(c=='(')
                stack.push(')');
            else if(c=='[')
                stack.push(']');
            else if(c=='{')
                stack.push('}');
            else if(stack.isEmpty()||stack.pop()!=c)
                return false;
        }
        return stack.isEmpty();
    }

思路如下:堆栈具有后进先出的特点。如果存在如下括号((【】)) 程序从左到右开始执行。遇到(【{就往堆栈中存入)】}。右边的括号一定和最近的左边的括号是同一个类型的,因此我们把堆栈顶上的值与当时的C进行比较并且删除。如果不相等那么返回false;如果符合题目要求,堆栈退出循环后为空。

posted @ 2018-03-20 20:01  血色黄昏X  阅读(110)  评论(0)    收藏  举报