I want to count the same words in my String array and print those counts as an integer array. For example:
input: String [] s = {"be", "be", "to", "onto", "onto", "onto"}
output 2,1,3
input: String words[] = {"be", "be", "not", "or", "to", "to", "to"}
output : 2,1,1,3
My code:
//O(n)
public static int [] MaxNumber(String [] arr)
{
int [] Number_arr=new int[11];
int count=1;
int j=0;
int k=0;
for(int i = 0; i<arr.length-1; i++)
{
if(arr[i].equals(arr[i+1]))
count++;
else{
Number_arr[j]=count;
j++;
count=1;
}
}
return Number_arr;
}
My input: String [] Sarr= {"be", "be", "not", "not", "not", "or", "to", "to", "to"};
My output is wrong: 2,3,1
correct output is: 2,3,1,3
How can I do that?
You forgot to add the count of the last sequence of equal Strings :
for(int i = 0; i<arr.length-1; i++)
{
if(arr[i].equals(arr[i+1]))
count++;
else{
Number_arr[j]=count;
j++;
count=1;
}
}
Number_arr[j]=count; // added
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With