Saturday, June 25, 2016

codingbat recursion 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.


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.length()<3)
  {
    return 0;
  }
  return count(str,0);
}

public int count(String str,int index)
{
    if(str.length()-index<3)
    {
      return 0;
    }
    return ((str.charAt(index)==str.charAt(index+2))?1:0) + count(str,index+1);
   
}

No comments:

Post a Comment