9) Write a recursive function (static method) called parenCleaner that takes a S
ID: 3844225 • Letter: 9
Question
9) Write a recursive function (static method) called parenCleaner that takes a String as a parameter, and returns a new String where all of the open parentheses (i.e. ‘(‘) have been moved to the beginning of the String and all of the closed parens (i.e. ‘)’) have been moved to the end of the String. This example question may help with this question (this is probably easier than you think). For example:
parenCleaner(“x()y()z(a)”) => “(((xyza)))”
parenCleaner(“f(x,y,z)”) => “(fx,y,z)”
parenCleaner(“pumpkins”) => “pumpkins”
public static String parenCleaner(String str) {
Explanation / Answer
public static String parenCleaner(String str)
{
String s="";
String end="";
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)=='(')
{
s = '('+s;
}
else if(str.charAt(i)==')')
{
end = end+')';
}
else
{
s = s+str.charAt(i);
}
}
return s+end;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.