Problem:
Given a string, return true if it is a nesting of zero or more pairs of parenthesis, like "(())" or "((()))". Suggestion: check the first and last chars, and then recur on what's inside them.
nestParen("(())") → true
nestParen("((()))") → true
nestParen("(((x))") → false
Solution:
public boolean nestParen(String str) { if (str.equals("")) return true; if (str.charAt(0) == '(' && str.charAt(str.length()-1) == ')') return nestParen(str.substring(1,str.length()-1)); else return false; }
thank you
ReplyDeletepublic boolean nestParen(String str) {
ReplyDeletereturn str.length() == 0 ||
('(' == str.charAt(0) && ')' == str.charAt(str.length() - 1))
&& nestParen(str.substring(1, str.length() - 1));
}
if(str.equals("")) return true;
ReplyDeleteif(str.charAt(0)!='(' || str.charAt(str.length()-1)!=')' ) return false;
else return nestParen(str.substring(1,str.length()-1));
I also added a check so that it would return false immediately if number of symbols is odd:
ReplyDeleteif (str.length() % 2 != 0) return false;
INgenious
Deleteif(str.startsWith("(")&&str.endsWith(")")){
ReplyDeletereturn nestParen(str.substring(1,str.length()-1));
}
return str.equals("");
}
public boolean nestParen(String str) {
ReplyDeletereturn str.length() == 0
|| str.charAt(0) == '('
&& str.charAt(str.length() - 1) == ')'
&& nestParen(str.substring(1, str.length() - 1));
}
public boolean nestParen(String str) {
ReplyDeleteif(str.startsWith("(")&&str.endsWith(")")){
return nestParen(str.substring(1,str.length() - 1));
}
return str.isEmpty();
}