Java > Recursion-1 > endX (CodingBat Solution)

Problem:

Given a string, compute recursively a new string where all the lowercase 'x' chars have been moved to the end of the string.

endX("xxre") → "rexx"
endX("xxhixx") → "hixxxx"
endX("xhixhix") → "hihixxx"


Solution:

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

1 comment:

  1. This is my solution : public String endX(String str) {

    if(str.length()==0) return "";

    if(str.charAt(0)=='x'){
    return endX(str.substring(1))+"x";
    }
    return str.charAt(0)+endX(str.substring(1));
    }

    ReplyDelete