settingsAccountsettings
Menusettings

Q: Largest Sequence of Equal Strings - Java Task

+6 votes

Write a program that enters an array of strings and finds in it the largest sequence of equal elements. If several sequences have the same longest length, print the leftmost of them. The input strings are given as a single line, separated by a space.

Examples:

Largest Sequence of Equal Strings

asked in Java category by user john7
edited by user golearnweb

1 Answer

+1 vote
 
Best answer

Here's my solution:

import java.util.ArrayList;
import java.util.Scanner;

public class Pr_03_LargestSequenceOfEqualStrings {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String[] array = scanner.nextLine().split(" ");
        ArrayList<String> list = new ArrayList<>();
        ArrayList<String> list2 = new ArrayList<>();

        int count = 0;
        int maxCount = 0;

        for (int i = 0; i < array.length; i++) {
            if (!list2.contains(array[i])) {
                for (int j = 0; j < array.length; j++) {
                    if (array[i].equals(array[j])) {
                        count++;
                    }
                }
                if (count > maxCount) {
                    maxCount = count;
                    list.clear();
                    list.add(array[i]);
                }
                count = 0;
            }
        }
        for (int i = 0; i < maxCount; i++) {
            System.out.print(list.get(0) + " ");
        }
    }
}

 

answered by user richard8502
selected by user golearnweb
...