Write a recursive method to remove the first occurrence of
/* Write a recursive method to remove the first occurrence of a specific String from a list. As an example, if your list initially contains AA BB CC DD BB KK and if your removee is BB, the returned list should contain AA CC DD BB KK after the removal. Return a new head. You must make sure that the parameter list remains intact after returning the new list to the main method. This method cannot contain any loop (that is, uses of for, while, do-while are prohibited IN Java). */
public static StringNode removeAStringFromMyList(StringNode M, String removee){
/* Write your code here */
Solution
The String class in Java has a method replaceFirst(String regex, String replacement) which replaces first occurrence of given regular expression with given replacement string.
import java.util.regex.Pattern;
public class RemoveRepeat{
public static void main(String[] args) {
//Input String
String input = \"AA BB CC DD BB KK\";
System.out.println(\"Input String :\" + input);
String result=removeAStringFromMyList(input,\"BB\");
//Output
System.out.println(\"Result:\" + result);
}
public static String removeAStringFromMyList(String M, String removee){
String result = M.replaceFirst(removee,\"\");
return result;
}
}
