Java > Recursion-1 > countHi (CodingBat Solution)

Problem:

Given a string, compute recursively (no loops) the number of times lowercase "hi" appears in the string.

countHi("xxhixx") → 1
countHi("xhixhix") → 2
countHi("hi") → 1


Solution:

public int countHi(String str) {
  if (str.length() < 2) return 0;
  if (str.substring(0,2).equals("hi")) return 1 + countHi(str.substring(1));
  else return countHi(str.substring(1));
}

9 comments:

  1. public int countHi(String str)
    {
    int count = 0;
    for(int i = 0; i< str.length() -1; i++)
    {
    if(str.substring(i,i+2).equals("hi"))
    count++;
    }
    return count;
    }

    ReplyDelete
    Replies
    1. It said no loops...why do you have a for loop?

      Delete
    2. Dumbass needs to learn how to use a fucking loop

      Delete
    3. Actually he needs to learn how to read directions

      Delete
    4. dont call him that

      Delete
  2. This is my solution. I just changed the if condition

    public int countHi(String str) {
    if(str.length()==0) return 0;


    if(str.length()>=2){
    if(str.substring(0,2).equalsIgnoreCase("hi")) {

    return 1+countHi(str.substring(2));

    }
    }

    return countHi(str.substring(1));
    }

    ReplyDelete
  3. public int countHi(String str) {
    if (str.length()<2)
    return 0;

    int count = (str.substring(0,2).equals("hi")) ? 1 : 0;

    return count + countHi(str.substring(1));
    }

    ReplyDelete

  4. public int countHi(String str) {
    if( str.length() < 2)
    return 0;
    String sub = "hi";
    if(str.substring(0,2).equals(sub))
    return 1 + countHi(str.substring(1));

    return countHi(str.substring(1));
    }

    ReplyDelete
  5. public int countHi(String str) {
    if (str.length() == 0) return 0;

    if (str.length() >= 2 && str.charAt(0) == 'h' && str.charAt(1) == 'i')
    return 1 + countHi(str.substring(2));

    else return countHi(str.substring(1));

    }

    ReplyDelete