Reputation: 45
I'm doing some recursion exercises and one has quite confused me. The problem stated that I should count the times "yo" has appeared in a string, but if the letter 'o' appears before the "yo", I'm not supposed to count it.
"yoyo" is counted as two, but "yooyo" is counted as one. I have done a code but it doesn't follow the condition of not counting the "yo" that has an 'o' before it. Thanks for the help!
My code:
import java.util.*;
public class Mp3
{
static int oui(String arr, int index)
{
int count = 0;
if(index >= arr.length())
return 0;
if(count == 0)
{
if(arr.charAt(index) == 'y')
{
if(arr.charAt(index + 1) == 'o')
count++;
else if(arr.charAt(index - 1) == 'o' && arr.charAt(index - 2) != 'y')
--count;
else
return count + oui(arr, index + 1);
}
}
return count + oui(arr, index + 1);
}
public static void main (String[] args)
{
String inp3 = "yoyooyoxhadjiohioyooyoyoxxyoyo";
int res3 = oui(inp3, 0);
System.out.println(inp3 + ":" + res3);
}
}
Upvotes: 1
Views: 123
Reputation: 1529
Make this simple:
let's assume index
represents 0-th index initially.
index
-ed and index+1
-ed character , if it is y
and o
increment count
by +1 and index
-ed value by +2;count
and increment index
-ed value by +1.caller :: getCountYo("yoyooyoxhadjiohioyooyoyoxxyoyo", 0);
private int getCountYo(String input, int index) {
int count = 0;
/* when you reach at the end of the string */
if(index == input.length() || index+1 == input.length()) {
return 0;
}else {
/* when "yo" found as a sub-string */
if(input.charAt(index) == 'y' && input.charAt(index+1) == 'o') {
count += getCountYo(input, index+2)+1;
}else if(input.charAt(index) != 'y') {
count += getCountYo(input, index+1);
}
}
return count;
}
Upvotes: 0
Reputation: 74
import java.util.*;
public class Mp3
{
static int oui(String arr, int index)
{
int count = 0;
if(index >= arr.length())
return 0;
if(arr.charAt(index)=='o' && arr.charAt(index+1)=='y'&&arr.charAt(index+2)=='o')
return count + oui(arr, index + 3);
if(arr.charAt(index) == 'y' && arr.charAt(index + 1) == 'o')
return count+ 1 +oui(arr, index + 2);
return count + oui(arr, index + 1);
}
public static void main (String[] args)
{
String inp3 = "yoyooyoxhadjiohioyooyoyoxxyoyo";
int res3 = oui(inp3, 0);
System.out.println(inp3 + ":" + res3);
}
}
**I tried not to change a lot from your code :
Upvotes: 3