Question:
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.
给定一个字符串只包含字符“(”、“)”、“{”、“}”,“[”和“]”,判断输入的字符串是有效的。
括弧必须以正确的顺序关闭,“()”和“()[ ] { }”都是有效的但”(]”和“([)]”不是。
Answer:
使用栈来做。
当是左半边括弧的时候入栈,右半边括弧的时候栈顶元素出栈,判断此时栈顶元素是否和字符串此次括弧对应,对应则顺利出栈,不对应则返回false。字符串遍历完成后栈为空时返回true,非空时返回false。
import java.util.Stack;
public class Solution {
public boolean isValid(String s){
Stack<Character> stack = new Stack<Character>();
int x = 0;
for(x=0;x<s.length();x++){
if(s.charAt(x)=='(' || s.charAt(x)=='[' || s.charAt(x)=='{'){
stack.push(s.charAt(x));
}
if(s.charAt(x)==')'){
if(stack.empty())
return false;
char ch = stack.pop();
if(ch=='(')
continue;
else return false;
}
else if(s.charAt(x)==']'){
if(stack.empty())
return false;
char ch = stack.pop();
if(ch=='[')
continue;
else return false;
}
else if(s.charAt(x)=='}'){
if(stack.empty())
return false;
char ch = stack.pop();
if(ch=='{')
continue;
else return false;
}
}
if(stack.empty()){
return true;
}
else return false;
}
}