Complete the sumPairs0 recursive method below to count the number of pairs found
ID: 3600452 • Letter: C
Question
Complete the sumPairs0 recursive method below to count the number of pairs found in a given string Assume that a "pair in a string is defined as two instances of a char separated by a char For example, the string "AxA" contains two A's separated by an 'x. The A's make a pair. Also, pair's can overlap For example, "AxAxA" contains 3 pairs -2 for A and I for x Recursively compute the number of pairs in the given string sumPairs("axa") returns 1 sumPairs("axax") returns 2 sumPairs("axbx") returns 1 public static int sumPairs (String str) fExplanation / Answer
Recursive Function
public static int sumPairs(String str) { // A recursive function having name sumPairs with String "str" as input with function return type as "int".
if(str.equals("") || str.length() <3) // Now check the condition as if the string is equals to or string length less than 3 than return "0"
return 0;
if(str.charAt(0) == str.charAt(2)) // checks the condition as if charAt(0) equal to charAt(2) i.e,checks the char value at 0th index is equal to the char value at 2nd index.
return 1 + sumPairs(str.substring(1)); // If it satisfies above condition than return 1+recursive function call with input substring with start index "1" i.e, string from 1st index is consider example if given string is "axax" so,it takes substring as "xax" and proceed.
else // else statement if both the above conditions are false than it returns a recursive function call as below.
return sumPairs(str.substring(1));
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.