20. Valid Parentheses

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. 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

My Solution:

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        for(char c : s.toCharArray()){
            if(c == '(' || c == '{' || c =='['){
                stack.push(c);
            }
            else if(c == ')'){
                if(!stack.empty() && stack.peek() == '(')
                    stack.pop();
                else
                    return false;
            }
            else if(c == ']'){
                if(!stack.empty() && stack.peek() == '[')
                    stack.pop();
                else
                    return false;
            }
            else if(c == '}'){
                if(!stack.empty() && stack.peek() == '{')
                    stack.pop();
                else
                    return false;
            }
        }
        return stack.empty();
    }
}

Solution #2:

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

Summary:

本题主要是进行符号匹配性检测,在数据结构的学习中有涉及。

主要思路是利用栈,利用foreach扫描字符串,遇到左符号则压栈,遇到右符号就查看栈顶符号是否匹配,若成功则将栈顶符号弹出,若失败则不匹配立即返回false。

若所有符号都扫描完毕且栈为空,则符号匹配成功。若中途匹配失败或扫描完毕时栈不为空,则符号匹配失败。

第二种解法是针对本题字符串中只有括号的情况,但若有其他字符则并不适用。

 

之前学习数据结构课程时主要是使用C++写ADT,这次接触了Java中自带的Stack类。

栈是Vector的一个子类,它实现了一个标准的后进先出的栈。

堆栈只定义了默认构造函数,用来创建一个空栈。 堆栈除了包括由Vector定义的所有方法,也定义了自己的一些方法。

序号方法描述
1boolean empty() 
测试堆栈是否为空。
2Object peek( )
查看堆栈顶部的对象,但不从堆栈中移除它。
3Object pop( )
移除堆栈顶部的对象,并作为此函数的值返回该对象。
4Object push(Object element)
把项压入堆栈顶部。
5

int search(Object element)
返回对象在堆栈中的位置,以 1 为基数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值