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.
Subscribe to see which companies asked this question
也是上古时期做的题了……其实现在要做就是一个stack的事,看到左括号就入栈,右括号就出栈,看是不是相对应的就好。以前的这种方法可以弃了。
public class Solution {
<span style="white-space:pre"> </span>public boolean isValid(String s) {
<span style="white-space:pre"> </span>String str = "";
<span style="white-space:pre"> </span>int len = s.length();
<span style="white-space:pre"> </span>for (int i = 0; i < len; i++) {
<span style="white-space:pre"> </span>// if(str.length()==0&&(s.charAt(i)==')'||s.charAt(i)=='}'||s.charAt(i)==']'))return
<span style="white-space:pre"> </span>// false;
<span style="white-space:pre"> </span>if (s.charAt(i) == '(')
<span style="white-space:pre"> </span>str += '(';
<span style="white-space:pre"> </span>if (s.charAt(i) == ')') {
<span style="white-space:pre"> </span>if (str.length() == 0 || str.charAt(str.length() - 1) != '(')
<span style="white-space:pre"> </span>return false;
<span style="white-space:pre"> </span>else
<span style="white-space:pre"> </span>str = str.substring(0, str.length() - 1);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>if (s.charAt(i) == '[')
<span style="white-space:pre"> </span>str += '[';
<span style="white-space:pre"> </span>if (s.charAt(i) == ']') {
<span style="white-space:pre"> </span>if (str.length() == 0 || str.charAt(str.length() - 1) != '[')
<span style="white-space:pre"> </span>return false;
<span style="white-space:pre"> </span>else
<span style="white-space:pre"> </span>str = str.substring(0, str.length() - 1);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>if (s.charAt(i) == '{')
<span style="white-space:pre"> </span>str += '{';
<span style="white-space:pre"> </span>if (s.charAt(i) == '}') {
<span style="white-space:pre"> </span>if (str.length() == 0 || str.charAt(str.length() - 1) != '{')
<span style="white-space:pre"> </span>return false;
<span style="white-space:pre"> </span>else
<span style="white-space:pre"> </span>str = str.substring(0, str.length() - 1);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>if (str.length() == 0)
<span style="white-space:pre"> </span>return true;
<span style="white-space:pre"> </span>return false;
<span style="white-space:pre"> </span>}
}