LeetCode - Easy - 20. Valid Parentheses

Topic

  • String
  • Stack

Description

https://leetcode.com/problems/valid-parentheses/

Given a string s 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.

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

Example 4:

Input: s = "([)]"
Output: false

Example 5:

Input: s = "{[]}"
Output: true

Constraints:

  • 1 <= s.length <= 10⁴
  • s consists of parentheses only ‘()[]{}’.

Analysis

Submission

package com.lun.easy;

import java.util.LinkedList;

public class ValidParentheses {

	// 方法一:我写的
	public boolean isValid1(String s) {
		LinkedList<Character> stack = new LinkedList<>();
		for (int i = 0; i < s.length(); i++) {

			char c = s.charAt(i);

			if (c == '(' || c == '{' || c == '[') {
				stack.push(c);
				continue;
			}

			if ((c == ')' || c == '}' || c == ']') && stack.isEmpty()) {
				return false;
			}

			char topOne = stack.peek();
			if (c == ')' && topOne == '(' || //
					c == '}' && topOne == '{' || //
					c == ']' && topOne == '[') {
				stack.pop();
				continue;
			}

			if ((c == ')' || c == '}' || c == ']')) {
				stack.push(c);
			}

		}

		return stack.isEmpty();
	}

	// 方法二:
	public boolean isValid2(String s) {
		LinkedList<Character> stack = new LinkedList<>();
		for (int i = 0; i < s.length(); i++) {

			char c = s.charAt(i);
			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();
	}

	// 方法三:
	public boolean isValid3(String s) {
		LinkedList<Character> stack = new LinkedList<>();
		// Iterate through string until empty
		for (int i = 0; i < s.length(); i++) {
			// Push any open parentheses onto stack
			if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{')
				stack.push(s.charAt(i));
			// Check stack for corresponding closing parentheses, false if not valid
			else if (s.charAt(i) == ')' && !stack.isEmpty() && stack.peek() == '(')
				stack.pop();
			else if (s.charAt(i) == ']' && !stack.isEmpty() && stack.peek() == '[')
				stack.pop();
			else if (s.charAt(i) == '}' && !stack.isEmpty() && stack.peek() == '{')
				stack.pop();
			else
				return false;
		}
		// return true if no open parentheses left in stack
		return stack.isEmpty();
	}

	// 方法四:
	public boolean isValid4(String s) {
		LinkedList<Integer> stack = new LinkedList<>();
		for (int i = 0; i < s.length(); i++) {
			int q = "(){}[]".indexOf(s.substring(i, i + 1));
			if (q % 2 == 1) {// )、}、]的情况
				if (stack.isEmpty() || stack.pop() != q - 1)
					return false;
			} else { // (、{、[的情况
				stack.push(q);
			}
		}
		return stack.isEmpty();
	}
}

Test

import static org.junit.Assert.*;
import org.junit.Test;

public class ValidParenthesesTest {

	@Test
	public void test() {
		ValidParentheses obj = new ValidParentheses();

		assertTrue(obj.isValid1("()"));
		assertTrue(obj.isValid1("()[]{}"));
		assertTrue(obj.isValid1("{[]}"));
		assertFalse(obj.isValid1("(]"));
		assertFalse(obj.isValid1("([)]"));
		
		assertTrue(obj.isValid2("()"));
		assertTrue(obj.isValid2("()[]{}"));
		assertTrue(obj.isValid2("{[]}"));
		assertFalse(obj.isValid2("(]"));
		assertFalse(obj.isValid2("([)]"));
		
		assertTrue(obj.isValid3("()"));
		assertTrue(obj.isValid3("()[]{}"));
		assertTrue(obj.isValid3("{[]}"));
		assertFalse(obj.isValid3("(]"));
		assertFalse(obj.isValid3("([)]"));
		
		assertTrue(obj.isValid4("()"));
		assertTrue(obj.isValid4("()[]{}"));
		assertTrue(obj.isValid4("{[]}"));
		assertFalse(obj.isValid4("(]"));
		assertFalse(obj.isValid4("([)]"));
		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值