算法题013 -- [Valid Parentheses] by java

题目

判断字符串中的括号是否有效。要求括号成对出现,并且括号顺序对应上。例如:[12(fgsf)4]-有效、{d[]df34}-有效、{f3[aer)}-无效、{3)32}-无效。

分析

依然考察的是代码能力,还有对栈的整体概念;有意思的是,这条题目的编码,相对而言其实会比之前一些中等难度的算法,还要难写,边界条件考虑的要很多;

思路

边界条件的考虑:考虑到存在这些括号字符的同时,也要考虑到不包含这些括号的字符串;
使用java中stack类;

代码

package algorithm013;

import java.util.Stack;

public class Algorithm013 {

	public static void main(String[] args) {
		String s = "asdf";// false
		String s2 = "()[]{}";// true
		String s3 = "{(1)2}3[]4";// true
		String s4 = "[}{()]";// false
		String s5 = "[12(fgsf)4]";// true
		String s6 = "{d[]df34}";// true
		String s7 = "{f3[aer)}";// false
		String s8 = "{3)32}";// false
		System.out.println(isValidParentheses(s));
		System.out.println(isValidParentheses(s2));
		System.out.println(isValidParentheses(s3));
		System.out.println(isValidParentheses(s4));
		System.out.println(isValidParentheses(s5));
		System.out.println(isValidParentheses(s6));
		System.out.println(isValidParentheses(s7));
		System.out.println(isValidParentheses(s8));
	}

	@SuppressWarnings("unchecked")
	public static boolean isValidParentheses(String test) {
		if (null != test && !"".equals(test)) {
			@SuppressWarnings("rawtypes")
			Stack stack = new Stack();
			boolean isValid = false;
			int length = test.length();
			for (int i = 0; i < length; i++) {
				char c = test.charAt(i);
				if('(' == c || '{' == c || '[' == c ) {
					isValid = true;
					stack.push(c);
					continue;
				}
				if(')' == c || '}' == c || ']' == c) {
					isValid = true;
					if(stack.isEmpty())
						return false;
					char pop = (char) stack.pop();
					if(!(('(' == pop && ')' == c) || ('{' == pop && '}' == c) || ('[' == pop && ']' == c))) {
						return false;
					}
				}
			}
			return isValid && stack.isEmpty();
		}
		return false;
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值