Java > Recursion-1 > countPairs (CodingBat Solution)

Problem:

We'll say that a "pair" in a string is two instances of a char separated by a char. So "AxA" the A's make a pair. Pair's can overlap, so "AxAxA" contains 3 pairs -- 2 for A and 1 for x. Recursively compute the number of pairs in the given string.

countPairs("axa") → 1
countPairs("axax") → 2
countPairs("axbx") → 1


Solution:

public int countPairs(String str) {
  if (str.equals("") || str.length() < 3) return 0;
  if (str.charAt(0) == str.charAt(2)) return 1 + countPairs(str.substring(1));
  else return countPairs(str.substring(1));
}


5 comments :

  1. This is my solution :


    public int countPairs(String str) {
    if(str.length()<3) return 0;

    if(str.length()>0 && str.charAt(0)==str.charAt(2)){


    return 1+ countPairs(str.substring(1));
    }

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

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

    int count = (str.charAt(0)==str.charAt(2)) ? 1 : 0;
    return count + countPairs(str.substring(1));
    }

    ReplyDelete
  3. if ( str.length() <= 2 ) return 0;
    if ( str.charAt(0) == str.charAt(2) ) return 1 +
    countPairs(str.substring(1));
    else return countPairs(str.substring(1));

    ReplyDelete
  4. private int countPairs(String str) {
    if(str.charAt(0) == str.charAt(2)){
    return 1 + countPairs(str.substring(1));
    }
    return countPairs(str.substring(1));
    }

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

      Delete

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