LeetCode 20 Valid Parentheses

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.

解题思路:这是一个简单的括号匹配问题,实现一个栈来进行匹配分析就可以。为了化简逻辑上的复杂度,我选择使用两个栈,一个栈作为符号存储,一个栈作为符号的下标存储,这也是为了便于匹配而实现的。通过下标栈的实现,不再需要单独的匹配的代码,只需要比较下标即可。当遇到后括号的时候,检索对应的下标栈,并将下标对应的数组值与当前括号比较,若相等,则说明括号匹配。如“()”第一个括号进入stack栈,check栈记录为0,遇到第二个括号的时候,check记录0对应的ch1值为")“,符合匹配。

代码如下:

public boolean isValid(String s) {
    char []stack = new char[1000];
    int []check = new int[1000]; //记录下标  便于匹配
    char []ch ={'(','{','['};
    char []ch1 = {')','}',']'};
    int index = 0;//数组下标
    for (int i = 0; i < s.length(); i++) {
		char c = s.charAt(i);
	if(c==ch[0]||c==ch[1]||c==ch[2]){
		if(c==ch[0]){
			check[index]=0;
		}
		if(c==ch[1]){
			check[index]=1;
		}
		if(c==ch[2]){
			check[index]=2;
		}
		stack[index++]=c;
		
	}else if(c==ch1[0]||c==ch1[1]||c==ch1[2]){
		if(index<=0){
			return false;
		}
		if(ch1[check[index-1]]==c){
			index--;
			continue;
		}else{
			return false;
		}
	}	
	}
    if(index>0){
    	return false;
    }
        return true;
    }


你可能感兴趣的:(LeetCode 20 Valid Parentheses)