Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
这道题不是很理解为什么这样做,Mark一下
public class Solution {
public static boolean isValid(String s) {
if(s == null || s.length() == 0 )
return true;
Stack<Character> st = new Stack<Character>();
for(char ch:s.toCharArray())
{
if (ch == '(')
st.push(')');
else if (ch == '{')
st.push('}');
else if (ch == '[')
st.push(']');
else if (st.isEmpty() || st.pop() != ch)
return false;
}
return st.empty();
}
public static void main(String[] args)
{
String s="()";
System.out.println(isValid(s));
}
}
网友评论