Problem:
Given a string that contains a single pair of parenthesis, compute recursively a new string made of only of the parenthesis and their contents, so "xyz(abc)123" yields "(abc)".
parenBit("xyz(abc)123") → "(abc)"
parenBit("x(hello)") → "(hello)"
parenBit("(xy)1") → "(xy)"
Solution:
public String parenBit(String str) { if (str.equals("")) return str; if (str.charAt(0) == '(') { if (str.charAt(str.length()-1) == ')') return str; else return parenBit(str.substring(0, str.length()-1)); } else return parenBit(str.substring(1)); }
CodingBat's solution:
ReplyDeletepublic String parenBit(String str) {
if (str.charAt(0) != '(') {
return parenBit(str.substring(1));
}
if (str.charAt(str.length()-1) != ')') {
return parenBit(str.substring(0, str.length()-1));
}
return str;
}
3 lines best solution)))
ReplyDeletepublic String parenBit(String str) {
if(str.length() == 0) return str;
if(str.charAt(0) == '(') return str.charAt(0) + str.substring(1, str.indexOf(')')+1);
return parenBit(str.substring(1));
}
I'm pretty sure you can't use indexOf() in this example. You should use recursion instead.
Deletereturn str.substring(str.indexOf("("),str.indexOf(")") + 1);
Delete**Without recursion**
@ЯКОВ ШТЕФФЕН nah, it works his solution.
ReplyDeleteA little bit stupid compared to codingbat's solution but it works:
ReplyDeletepublic String parenBit(String str) {
if (str.length() == 0) return str;
if (str.charAt(0) == '(')
return "(" + parenBit("*" + str.substring(1));
if (str.length() > 1 && str.charAt(0) == '*')
return str.charAt(1) == ')' ? ")" : str.charAt(1) + parenBit("*" + str.substring(2));
else
return parenBit(str.substring(1));
}
hi From Egypt:
ReplyDeletepublic String parenBit(String str) {
if(str.length() > 0){
return str.substring(str.indexOf('('), str.indexOf(')')+1);}
else return "";
}
public String parenBit(String str) {
ReplyDeleteif (str.charAt(0) == '(' && str.charAt(str.length() - 1) == ')')
{
return str;
}
else
{
if (str.charAt(0) == '(')
{
return parenBit(str.substring(0, str.length() - 1));
}
else if (str.charAt(str.length() - 1) == ')')
{
return parenBit(str.substring(1));
}
else
{
return parenBit(str.substring(1, str.length() - 1));
}
}
}
My solution with cheats
ReplyDeletepublic String parenBit(String str) {
if(str.length() < 2) return str;
if(str.startsWith("("))
return str.substring(str.indexOf("("), str.indexOf(")")) + ")";
return parenBit(str.substring(1));
}
int s1=str.indexOf('(');
ReplyDeleteint s2=str.indexOf(')');
return str.substring(s1,s2+1);
return str.substring(str.indexOf("("), str.indexOf(")") +1 );
ReplyDelete