As part of a homework assignment, I need to use recursion to solve a problem. I have written a method that works, but am not quite sure if I have applied the concept for recursion correctly in this situation. I have included the problem description and my code with comments (along with a main() runner program). Please let me know if this is considered "recursion."
Assignment:
Given a string, return recursively a "cleaned" string where adjacent chars that are the same have been reduced to a single char. So "yyzza" yields "yza".
stringClean("yyzzza") -> "yza"
stringClean("abbbcdd") -> "abcd"
stringClean("Hello") -> "Helo"
public static void main(String[] args) {
System.out.println("Cleaning yyzzza: " + stringClean("yyzzza"));
System.out.println("Cleaning abbbcdd: " + stringClean("abbbcdd"));
System.out.println("Cleaning Hello: " + stringClean("Hello"));
}
/**
* Recursive method to remove consecutive duplicate characters from a
* string. Beginning at string index 1, compare to previous string
* character. If they match (case sensitive) call method again with the
* character removed from the string. Character is removed by concatenating
* the substring up to that duplicate character with the remainder of the
* string after that character.
* @param str // the string to check for consecutive duplicate characters
* @return a string with no consecutive duplicates
*/
private static String stringClean(String str) {
// Search for a duplicate character
for(int i = 1; i < (str.length()); i++) {
if(str.charAt(i-1) == str.charAt(i))
// Remove the duplicate character and search again
return stringClean(str.substring(0, i-1) +
str.substring(i, str.length()));
}
// Base case has no duplicate characters
return str;
}

New Topic/Question
Reply



MultiQuote









|