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)); }
This is my solution :
ReplyDeletepublic 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));
}
public int countPairs(String str) {
ReplyDeleteif (str.length()<3)
return 0;
int count = (str.charAt(0)==str.charAt(2)) ? 1 : 0;
return count + countPairs(str.substring(1));
}
if ( str.length() <= 2 ) return 0;
ReplyDeleteif ( str.charAt(0) == str.charAt(2) ) return 1 +
countPairs(str.substring(1));
else return countPairs(str.substring(1));
private int countPairs(String str) {
ReplyDeleteif(str.charAt(0) == str.charAt(2)){
return 1 + countPairs(str.substring(1));
}
return countPairs(str.substring(1));
}
public int countPairs(String str) {
Deleteif (str.length() <= 2){
return 0;
}
return (str.charAt(0) == str.charAt(2))?
1 + countPairs(str.substring(1)) :countPairs(str.substring(1));
}