Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count equals string in String sort array

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?

like image 831
ReGiNa Avatar asked Apr 28 '26 08:04

ReGiNa


1 Answers

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
like image 135
Eran Avatar answered Apr 29 '26 23:04

Eran