Java > Recursion-1 > count11 (CodingBat Solution)

Problem:

Given a string, compute recursively (no loops) the number of "11" substrings in the string. The "11" substrings should not overlap.

count11("11abc11") → 2
count11("abc11x11x11") → 3
count11("111") → 1


Solution:

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


4 comments :

  1. public int count11(String str) {
    if (str.length()<2)
    return 0;

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

    return count + count11(str.substring(jump));
    }

    ReplyDelete
  2. public int count11(String str) {
    if(str.length() <= 1){
    return 0;
    }
    return (str.charAt(0) == '1' && str.charAt(1) == '1')?
    1 + count11(str.substring(2)): count11(str.substring(1));
    }

    ReplyDelete
  3. public int count11(String str) {
    if(str.length() <= 1){
    return 0;
    }
    if(str.charAt(0) == '1' && str.charAt(1) == '1'){
    return 1 + count11(str.substring(2));
    }
    return count11(str.substring(1));
    }

    ReplyDelete
  4. public int count11(String str) {
    if (str.contains("11")) return 1 + count11(str.substring(str.indexOf("11")+2));
    else return 0;
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact