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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cjh_android/article/details/84108790

题目

判断字符串中的括号是否有效。要求括号成对出现,并且括号顺序对应上。例如:[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;
	}
}

猜你喜欢

转载自blog.csdn.net/cjh_android/article/details/84108790