題目:

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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public static boolean isValid(String s) {
	Stack<Character> stack = new Stack<>();
	if(s.length()%2!=0)
		return false;
	
	for(int i=0;i<s.length();i++){
		char c = s.charAt(i);
		
		if(c == '(')
			stack.push(')');
		else if(c == '[')
			stack.push(']');
		else if(c == '{')
			stack.push('}');
		else{
			if(stack.isEmpty())
				return false;
			
			char t = stack.pop();
			if(t != c)
				return false;
		}
		
	}
	if(stack.empty())
		return true;
	else
		return false;
}

 

 

 

arrow
arrow
    文章標籤
    leetcode Easy
    全站熱搜

    Lung-Yu,Tsai 發表在 痞客邦 留言(0) 人氣()