leetcode: 20. Valid Parentheses

Difficulty

Easy

Description

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true
Example 2:

Input: "()[]{}"
Output: true
Example 3:

Input: "(]"
Output: false
Example 4:

Input: "([)]"
Output: false
Example 5:

Input: "{[]}"
Output: true

Solution

Time Complexity: O(n)
Space Complexity: O(n)

class Solution {
    public boolean isValid(String s) {
        if (s.length() == 0)
        {
			return true;
        } 

		if (s.length() % 2 != 0)
        {
			return false;
        }

		List<Character> list = new ArrayList<>();

		for(int i = 0; i < s.length(); i++)
		{
			switch (s.charAt(i))
			{
			case '(':
				list.add('(');
				break;
			case '[':
				list.add('[');
				break;
			case '{':
				list.add('{');
				break;
			case ')':
				if (!isTheSame(')', 1, list)) return false;
				break;
			case ']':
				if (!isTheSame(']', 2, list)) return false;
				break;
			case '}':
				if (!isTheSame('}', 2, list)) return false;
				break;
			}
		}

		if (list.size() == 0)
		{
			return true;
		} else {
			return false;
		}

    }

	public boolean isTheSame(char c, int n, List<Character> list) {
		if (list.size() != 0)
		{
			if (list.get(list.size() - 1) == c - n)
			{
				list.remove(list.size() - 1);
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
}

猜你喜欢

转载自blog.csdn.net/baidu_25104885/article/details/86665007