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.
使用栈的思想。public boolean isValid(String s) { String subStr = ""; for(int i = 0 ; i < s.length(); i ++){ char ch = s.charAt(i); if(ch == '(' || ch == '[' || ch == '{'){ subStr = subStr + ch; }else if(subStr.length() == 0){ return false; }else if(ch == ')'){ char cs = subStr.charAt(subStr.length() - 1); if(cs == '('){ if(subStr.length() == 1){ subStr = ""; }else{ subStr = subStr.substring(0, subStr.length()-1); } }else{ return false; } }else if(ch == ']'){ char cs = subStr.charAt(subStr.length() - 1); if(cs == '['){ if(subStr.length() == 1){ subStr = ""; }else{ subStr = subStr.substring(0, subStr.length()-1); } }else{ return false; } }else if(ch == '}'){ char cs = subStr.charAt(subStr.length() - 1); if(cs == '{'){ if(subStr.length() == 1){ subStr = ""; }else{ subStr = subStr.substring(0, subStr.length()-1); } }else{ return false; } } } if(subStr == ""){ return true; }else{ return false; } }
Valid Parentheses,布布扣,bubuko.com
原文:http://blog.csdn.net/u010378705/article/details/31394161