[lintcode easy]Valid Parentheses
Valid Parentheses
Given a string containing just the characters '(', ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
Example
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
////
Java的String中的subString()方法
方法如下:
public String substring(int beginIndex, int endIndex)
第一个int为开始的索引,对应String数字中的开始位置,
第二个是截止的索引位置,对应String中的结束位置
1、取得的字符串长度为:endIndex - beginIndex;
2、从beginIndex开始取,到endIndex结束,从0开始数,其中不包括endIndex位置的字符
如:
"hamburger".substring(4, 8) returns "urge"
"smiles".substring(1, 5) returns "mile"
////////
public class Solution { /** * @param s A string * @return whether the string is a valid parentheses */ public boolean isValidParentheses(String s) { if(s==null) return false; if(s.length()%2 !=0) return false; // Write your code here char[] c=s.toCharArray(); for(int i=1;i<s.length();i++) { boolean r1= c[i-1]=='(' && c[i]==')'; boolean r2= c[i-1]=='{' && c[i]=='}'; boolean r3= c[i-1]=='[' && c[i]==']'; if(r1||r2||r3) { String s1=s.substring(0,i-1)+s.substring(i+1); if(s1.length()==0) return true; else return isValidParentheses(s1); } } return false; } }