[LeetCode] 20. Valid Parentheses

题目链接:传送门

Description

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.

Solution

题意:

给定一个包含'(', ')', '{', '}', '[', ']'的括号序列,判断是否合法

思路:

经典的括号匹配问题,直接用一个栈维护即可

class Solution {
public:
    bool isValid(string s) {
        unordered_map<char, int> val = {
            {'(', 0}, {')', 0},
            {'[', 1}, {']', 1},
            {'{', 2}, {'}', 2}
        };
        stack<int> Stack;
        for (int i = 0; i < s.length(); i++) {
            if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
                Stack.push(val[s[i]]);
            } else {
                if (Stack.empty() || Stack.top() != val[s[i]])  return false;
                Stack.pop();
            }
        }
        return Stack.empty();
    }
};

补充:

看了下 Discuss 里面基本上都是用栈,关键在实现的手法上有些许差别,贴几个参考:

(1) Short java solution

public 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();
}

(2) 12 lines of Java

public class Solution {
    public boolean isValid(String s) {
        Stack<Integer> p = new Stack<>();
        for(int i = 0; i < s.length(); i++) {
            int q = "(){}[]".indexOf(s.substring(i, i + 1));
            if(q % 2 == 1) {
                if(p.isEmpty() || p.pop() != q - 1) return false;
            } else p.push(q);
        }
        return p.isEmpty();
    }
}
posted @ 2018-02-17 01:41  酒晓语令  阅读(107)  评论(0编辑  收藏  举报