Advertisement
dimipan80

3. Largest Sequence of Equal Strings

Sep 12th, 2014
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.76 KB | None | 0 0
  1. /* Write a program that enters an array of strings and finds in it
  2.  * the largest sequence of equal elements.
  3.  * If several sequences have the same longest length, print the leftmost of them.
  4.  * The input strings are given as a single line, separated by a space. */
  5.  
  6. import java.util.Scanner;
  7.  
  8. public class _03_LargestSequenceOfEqualStrings {
  9.  
  10.     public static void main(String[] args) {
  11.         // TODO Auto-generated method stub
  12.         Scanner scan = new Scanner(System.in);
  13.         System.out.println("Enter the Elements of your Array on single line, separated by a space:");
  14.         String inputLine = scan.nextLine();
  15.  
  16.         if (!inputLine.isEmpty()) {
  17.             String[] stringArr = inputLine.split("[\\s]+");
  18.             printTheLargestSequenceOfEqualStrings(stringArr);
  19.         } else {
  20.             System.out.println("Error! - Input Array of Strings is Empty!!!");
  21.         }
  22.     }
  23.  
  24.     private static void printTheLargestSequenceOfEqualStrings(String[] strings) {
  25.         System.out.println("The Largest Sequence of Equal elements in your Array is:");
  26.  
  27.         int maxSizeOfSeq = 1;
  28.         int startIndex = 0;
  29.  
  30.         if (strings.length > 1) {
  31.             int countEquals = 1;
  32.             int indexEquals = 0;
  33.             String previous;
  34.  
  35.             for (int i = 1; i < strings.length; i++) {
  36.                 previous = strings[i - 1];
  37.                 if (strings[i].equals(previous)) {
  38.                     countEquals++;
  39.                 } else {
  40.                     if (countEquals > maxSizeOfSeq) {
  41.                         maxSizeOfSeq = countEquals;
  42.                         startIndex = indexEquals;
  43.                     }
  44.  
  45.                     indexEquals = i;
  46.                     countEquals = 1;
  47.                 }
  48.             }
  49.  
  50.             if (countEquals > maxSizeOfSeq) {
  51.                 maxSizeOfSeq = countEquals;
  52.                 startIndex = indexEquals;
  53.             }
  54.  
  55.         }
  56.  
  57.         for (int i = startIndex; i < startIndex + maxSizeOfSeq - 1; i++) {
  58.             System.out.print(strings[i] + " ");
  59.         }
  60.  
  61.         System.out.println(strings[startIndex + maxSizeOfSeq - 1]);
  62.     }
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement