Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* 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. */
- import java.util.Scanner;
- public class _03_LargestSequenceOfEqualStrings {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Scanner scan = new Scanner(System.in);
- System.out.println("Enter the Elements of your Array on single line, separated by a space:");
- String inputLine = scan.nextLine();
- if (!inputLine.isEmpty()) {
- String[] stringArr = inputLine.split("[\\s]+");
- printTheLargestSequenceOfEqualStrings(stringArr);
- } else {
- System.out.println("Error! - Input Array of Strings is Empty!!!");
- }
- }
- private static void printTheLargestSequenceOfEqualStrings(String[] strings) {
- System.out.println("The Largest Sequence of Equal elements in your Array is:");
- int maxSizeOfSeq = 1;
- int startIndex = 0;
- if (strings.length > 1) {
- int countEquals = 1;
- int indexEquals = 0;
- String previous;
- for (int i = 1; i < strings.length; i++) {
- previous = strings[i - 1];
- if (strings[i].equals(previous)) {
- countEquals++;
- } else {
- if (countEquals > maxSizeOfSeq) {
- maxSizeOfSeq = countEquals;
- startIndex = indexEquals;
- }
- indexEquals = i;
- countEquals = 1;
- }
- }
- if (countEquals > maxSizeOfSeq) {
- maxSizeOfSeq = countEquals;
- startIndex = indexEquals;
- }
- }
- for (int i = startIndex; i < startIndex + maxSizeOfSeq - 1; i++) {
- System.out.print(strings[i] + " ");
- }
- System.out.println(strings[startIndex + maxSizeOfSeq - 1]);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement