【Leetcode-20】Valid Parentheses

【Leetcode-20】Valid Parentheses

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

An input string is valid if:

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

public class Solution20 {
	 public boolean isValid(String s) {
	    	Stack<Character> stack=new Stack<Character>();
	    	int len=s.length();
	    	for(int i=0;i<len;i++) {
	    		if(s.charAt(i)=='['||s.charAt(i)=='('||s.charAt(i)=='{') {
	    			stack.push(s.charAt(i));
	    		}else if (s.charAt(i)==']') {
	    			//从栈中取出一个元素
	                if(stack.empty()==true){
	                    return false;
	                }
	    			char ch=stack.pop();
	    			if(ch!='[') {
	    				return false;
	    				
	    			}
	    			
	    		}else if(s.charAt(i)==')') {
	                if(stack.empty()==true){
	                    return false;
	                }
	    			char ch=stack.pop();
	    			if(ch!='(') {
	    				return false;
	    				
	    			}
	    			
	    		}else if(s.charAt(i)=='}'){
	                if(stack.empty()==true){
	                    return false;
	                }
	    			char ch=stack.pop();
	    			if(ch!='{') {
	    				return false;
	    				
	    			}
	    			
	    		}
	    	}
	    	
	    	if(stack.empty()==true) {
	    		return true;
	    	}
	    	return false;
	        
	    }


}

发布了34 篇原创文章 · 获赞 4 · 访问量 1341

猜你喜欢

转载自blog.csdn.net/zj20165149/article/details/103936503