Leetcode刷题记——20. 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.

Subscribe to see which companies asked this question

二、解题思路:

这就是道典型的括号匹配题,用栈的思想喽:

1、用栈的思想,遇到所有左括号进栈;遇到所有的右括号,出栈比较括号是否匹配(注意此处当栈空的时候输出false),不匹配输出false,匹配循环继续;遇到其他非括号字符,继续循环。

2、当循环结束,栈空为true;栈非空为false。

宝宝我又是提交第二次才过,好啦 我知道自己菜到无法形容,所以才被鄙视。。。

三、源码:

public class Solution 
{ 
	public static final char LEFT_BIG = '{';
	public static final char RIGHT_BIG = '}';
	public static final char LEFT_MID = '[';
	public static final char RIGHT_MID = ']';
	public static final char LEFT_SMALL = '(';
	public static final char RIGHT_SMALL= ')';
    public boolean isValid(String s)
    {
    	int n = 0;//n记录数组下标;栈顶指针
    	char[] temp = new char[s.length()];//栈
    	for (int i = 0; i < s.length(); i ++)
    	{
    		if (s.charAt(i) == LEFT_BIG || s.charAt(i) == LEFT_MID || s.charAt(i) == LEFT_SMALL)
    		{
    			temp[n++] = s.charAt(i);
    			continue;
    		}
    		else if (s.charAt(i) == RIGHT_BIG)
    		{
    			if (n == 0) return false;
    			if (temp[--n] == LEFT_BIG)
    				continue;
    			else return false;
    			
    		}	
    		else if (s.charAt(i) == RIGHT_MID)
    		{
    			if (n == 0) return false;
    			if (temp[--n] == LEFT_MID) continue;
    			else return false;
    		}	
    		else if (s.charAt(i) == RIGHT_SMALL)
    		{
    			if (n == 0) return false;
    			if (temp[--n] == LEFT_SMALL) continue;
    			else return false;
    		}	
    		else
    			continue;
    		
    	}
    	if (n == 0) return true;
		else return false;
    }
    public static void main(String args[])
    {
    	String a = "(a])";
    	Solution solution = new Solution();
    	System.out.println(solution.isValid(a));
    	
    	
    }
}


你可能感兴趣的:(刷刷刷题)