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));
}

1. CodingBat's solution:

public 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;
}

2. 3 lines best solution)))

public 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));
}

1. I'm pretty sure you can't use indexOf() in this example. You should use recursion instead.

2. return str.substring(str.indexOf("("),str.indexOf(")") + 1);
**Without recursion**

3. @ЯКОВ ШТЕФФЕН nah, it works his solution.

4. A little bit stupid compared to codingbat's solution but it works:

public 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));
}

5. hi From Egypt:
public String parenBit(String str) {
if(str.length() > 0){
return str.substring(str.indexOf('('), str.indexOf(')')+1);}
else return "";

}

6. public String parenBit(String str) {
if (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));
}
}
}

7. My solution with cheats

public 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));
}

8. int s1=str.indexOf('(');
int s2=str.indexOf(')');
return str.substring(s1,s2+1);

9. return str.substring(str.indexOf("("), str.indexOf(")") +1 );