`
淡淡的一抹
  • 浏览: 18983 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Valid Parentheses

 
阅读更多
题目描述
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

解题思路
本题考查的是判断一个字符串是否为正确括号的使用,即括号要成对使用,并且使用的前后顺序要正确。

相关知识点
(1)Java中的栈
 boolean empty();//测试堆栈是否为空。
 
 E peek();//查看堆栈顶部的对象,但不从堆栈中移除它。
 
 E pop();//移除堆栈顶部的对象,并作为此函数的值返回该对象。
 
 E push(E item);//把项压入堆栈顶部。


自己的代码
package leetcode;

import java.util.Stack;

public class ValidParentheses {
	public boolean isValid(String s) {
		if(s == null) return false;
		if(s.length() == 0) return false;
		if(s.length()%2 != 0) return false;
		
		boolean isValided = true;
		Stack<Character> stack = new Stack<Character>();
		for(int i = 0; i < s.length(); i++){
			char c = s.charAt(i);
			if(c == '(') stack.add(')');
			else if(c == '[') stack.add(']');
			else if(c== '{') stack.add('}');
			else if(c == ')' || c == ']' || c == '}'){
				if(stack.empty() || stack.pop() != c){
					isValided = false;
					break;
				}
			}
			else{
				isValided = false;
				break;
			}
		}
		if(!stack.empty()) isValided = false;
		return isValided;
    }
	
	public static void main(String[] args) {
		//String s = null;
		//String s = "";
		//String s = " ";
		//String s = "  ";
		//String s = "()";
		//String s = "[]";
		//String s = "{}";
		//String s = "(]";
		//String s = "([)]";
		//String s = "([])";
		String s = "((";
		
		
		ValidParentheses vp = new ValidParentheses();
		System.out.println(vp.isValid(s));
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics