面试手撕代码 判断符号字符串是否有效

需要配对,很明显 用栈 

① 开始思路

public static boolean isValid(String s) {	

		Stack stack = new Stack();
	
		str="([{";
		str1=")]}";
		
		for (int i = 0; i < s.length(); i++) {
			char curr = s.charAt(i);
			
			if (str.indexof(curr)!=-1) {
				stack.push(curr);
			} else if (str1.indexof(curr)!=-1) {
                    //栈顶的是左半括号,且和要比较的 有半括号 配对 ,配对成功,弹出栈顶的左半括号
				if (!stack.empty() && str.indexof(stack.peek()) == str1.indexof(curr)) {
					stack.pop();
				} else {
					return false;
				}
			}
		}
		return stack.empty();
}

 

② 用map 更优雅

public static boolean isValid(String s) {
	HashMap map = new HashMap();
	map.put('(', ')');
	map.put('[', ']');
	map.put('{', '}');
	Stack stack = new Stack();
	for (int i = 0; i < s.length(); i++) {
		char curr = s.charAt(i);
		if (map.keySet().contains(curr)) {
			stack.push(curr);
		} else if (map.values().contains(curr)) {
			if (!stack.empty() && map.get(stack.peek()) == curr) {
			stack.pop();
			} else {
				return false;
			}
		}
	}
	return stack.empty();
}

 

你可能感兴趣的:(JAVA,笔试题库)