Java > Recursion-1 > countAbc (CodingBat Solution)

Problem:

Count recursively the total number of "abc" and "aba" substrings that appear in the given string.

countAbc("abc") → 1
countAbc("abcxxabc") → 2
countAbc("abaxxaba") → 2


Solution:

public int countAbc(String str) {
  if (str.length() < 3) return 0;
  if (str.substring(0,3).equals("abc") || str.substring(0,3).equals("aba"))
    return 1 + countAbc(str.substring(1));
  else
    return countAbc(str.substring(1));
}


7 comments :

  1. wouldn't it be more efficient in line 4 to make it substring(2) as its impossible for the second place to be the start of another "true" statement.

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

    int count = 0;
    if (str.substring(0,2).equals("ab") && (str.charAt(2)=='a' || str.charAt(2)=='c'))
    count++;

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

    ReplyDelete
  3. public int countAbc(String str) {
    if (str.length() < 3)
    {
    return 0;
    }
    else
    {
    if (str.substring(0, 3).equals("abc") || str.substring(0, 3).equals("aba"))
    {
    return 1 + countAbc(str.substring(2));
    }
    else
    {
    return countAbc(str.substring(1));
    }
    }
    }

    ReplyDelete
  4. public int countAbc(String str) {
    if(str.isEmpty()){
    return 0;
    }
    if (str.length() >= 3
    && str.charAt(0) == 'a'
    && str.charAt(1) == 'b'
    && str.charAt(2) == 'a'
    != (str.charAt(2) == 'c')){
    return 1 + countAbc(str.substring(2));
    }
    return countAbc(str.substring(1));
    }

    ReplyDelete
  5. public int countAbc(String str) {

    if (str.length() < 3) return 0;

    if (str.substring(0,3).equals("abc") || str.substring(0,3).equals("aba"))

    return 1 + countAbc(str.substring(1));

    else

    return countAbc(str.substring(1));

    }

    ReplyDelete
  6. public int countAbc(String str) {
    if(str.length() < 3) return 0;
    if(str.startsWith("abc") || str.startsWith("aba"))
    return 1 + countAbc(str.substring(2));
    return countAbc(str.substring(1));
    }

    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