LeetCode 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.

方法一、找到第一个右括号,然后和左边的字符一起借助哈希表映射,判断是否成对。

 1     public static boolean isValid(String s) {

 2         if(s.length()<2 || s.length()%2==1)

 3             return false;

 4         Map<Character,Integer> map=new HashMap<Character,Integer>();

 5         map.put('(', 1);

 6         map.put(')', 9);

 7         map.put('{', 2);

 8         map.put('}', 8);

 9         map.put('[', 3);

10         map.put(']', 7);

11         boolean result=true;

12         for(int i=0;i<s.length();i++)

13         {

14             if(map.get(s.charAt(i))<5)

15             {

16                 if(i==s.length()-1)//防止越界,也没找到,最后一个肯定不是右括号

17                     return false;

18                 continue;

19             }

20             if(i-1<0)//排除出现}{的情况

21                 return false;

22             if(map.get(s.charAt(i-1))+map.get(s.charAt(i))==10)

23             {

24                 s=s.substring(0, i-1)+(i+1<s.length()?s.substring(i+1, s.length()):"");

25                 if(s.length()!=0)

26                 {

27                     result=isValid(s);

28                 }

29                 break;

30             }

31             else

32             {

33                 result=false;

34             }

35             

36         }

37         return result;

38     }

方法二,栈

    public boolean isValid(String s) {

        if(s.length()<1 || s.length()%2!=0)

            return false;

        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));

                if(i==s.length()-1)//最后一个

                    return false;

                continue;

            }

            switch (s.charAt(i)) {

            case '}':

                if(stack.size()==0)

                    return false;

                Character c1=stack.pop();

                if(c1!='{')

                {

                    return false;

                }

                break;

            case ')':

                if(stack.size()==0)

                    return false;

                Character c2=stack.pop();

                if(c2!='(')

                {

                    return false;

                }

                break;

            case ']':

                if(stack.size()==0)

                    return false;

                Character c3=stack.pop();

                if(c3!='[')

                {

                    return false;

                }

                break;

            }

        }

        return true;

    }

 

你可能感兴趣的:(LeetCode)