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.

 

import java.util.HashMap;
import java.util.Stack;

/**
 * Created by chris on 14/11/23.
 */
public class ValidParentheses {
    public boolean isValid(String s) {

        Stack <Character> stack = new Stack<Character>();
        HashMap<Character, Character> map = new HashMap<Character, Character>();
        map.put('(',')');
        map.put('[',']');
        map.put('{','}');

        for (int i = 0; i < s.length(); i++) {
            switch (s.charAt(i)){
                case  '(':
                case '{':
                case '[':
                    stack.push(s.charAt(i));
                    break;
                case  '}':
                case ')':
                case ']':
                    if (!stack.isEmpty() && s.charAt(i) == map.get(stack.peek()))
                        stack.pop();
                    else if (stack.isEmpty() )
                        return false;
                    break;
            }
        }
        if (stack.isEmpty())
            return true;

        return false;
    }

}
Tagged on: , ,

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据