LeetCode-Valid Parentheses

题目:https://oj.leetcode.com/problems/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.

源码:Java版本
算法分析:时间复杂度O(n!),空间复杂度O(n)

public class Solution {
    public boolean isValid(String s) {
		Stack<Character> stack = new Stack<Character>();
		for (int i = 0; i < s.length(); i++) {
			switch (s.charAt(i)) {
			case '(':
				stack.push('(');
				break;
			case '{':
				stack.push('{');
				break;
			case '[':
				stack.push('[');
				break;
			case ')':
			 if(!stack.isEmpty() && stack.peek()=='(') {
			        stack.pop();
			    }else {
			        return false;
			    }
				break;
			case '}':
			    if(!stack.isEmpty() && stack.peek()=='{') {
			        stack.pop();
			    }else {
			        return false;
			    }
				break;
			case ']':
			    if(!stack.isEmpty() && stack.peek()=='[') {
			        stack.pop();
			    }else {
			        return false;
			    }
				break;
            default:
                return false;
			}
		}
		if(stack.isEmpty) {
		    return true;
		}else {
		    return false;
		}
	}
}

你可能感兴趣的:(LeetCode)