Java > Recursion-1 > noX (CodingBat Solution)

Problem:

Given a string, compute recursively a new string where all the 'x' chars have been removed.

noX("xaxb") → "ab"
noX("abc") → "abc"
noX("xx") → ""


Solution:

public String noX(String str) {
  if (str.equals("")) return str;
  if (str.charAt(0) == 'x') return noX(str.substring(1));
  else return str.charAt(0) + noX(str.substring(1));
}

2 comments:

  1. public String noX(String str) {
    int i = str.indexOf('x');
    if(i==-1)return str;
    str = str.substring(0,i)+str.substring(i+1);
    return noX(str);
    }

    ReplyDelete
  2. public String noX(String str) {
    if(str.indexOf("x")<0) return str;
    return noX(str.substring(0, str.indexOf("x")) + str.substring(str.indexOf("x")+1));
    }

    ReplyDelete