LeetCode20. 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.


思路

設計一個棧數據結構,每當遇到左括號時候壓入棧,遇到有括號時候判斷棧頂元素是不是一個與之匹配的左括號,如果是則出站,如果否則返回FALSE;最後若棧爲空則返回TRUE,否則返回FALSE。


代碼

public class Solution {
    public boolean isValid(String s) {
        char [] stack  = new char[10000];
        int top = -1;
        if(s.charAt(0) == '}' || s.charAt(0) == ']'  || s.charAt(0) == ')' )	return false;
        int i = 0;
        while(i < s.length()){
        	char c = s.charAt(i);
        	if(c == '{' || c == '[' || c == '('){
        		++top;
        		stack[top] = c;
        	}
        	else{
        	    if(top < 0)	return false;
        		char t = stack[top];
        		if(t == '{' && c == '}'){
        			--top;
        		}
        		else if(t == '[' && c == ']'){
        			--top;
        		}
        		else if(t == '(' && c == ')'){
        			--top;
        		}
        		else{
        			return false;
        		}
        	}
        	++i;
        }
        if(top == -1)	return true;
        else	return false;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章