|
| 1 | +package ch_22; |
| 2 | + |
| 3 | +import java.util.Scanner; |
| 4 | + |
| 5 | +/** |
| 6 | + * 22.5 (Same-number subsequence) Write an O(n) program that prompts the user to |
| 7 | + * enter a sequence of integers ending with 0 and finds the longest subsequence |
| 8 | + * with the same number. Here is a sample run of the program: |
| 9 | + * Enter a series of numbers ending with 0: |
| 10 | + * 2 4 4 8 8 8 8 2 4 4 0 |
| 11 | + * The longest same number sequence starts at index 3 with 4 values of 8 |
| 12 | + */ |
| 13 | +public class Exercise22_05 { |
| 14 | + private void findSubsequence(String[] tokens) { |
| 15 | + int longest = 0; |
| 16 | + int longestStartIndex = 0; |
| 17 | + int count = 1; |
| 18 | + int value = 0; |
| 19 | + int startIndex = 0; |
| 20 | + |
| 21 | + for (int i = 0; i < tokens.length - 1; i++) { |
| 22 | + int curr = Integer.parseInt(tokens[i]); |
| 23 | + int next = Integer.parseInt(tokens[i + 1]); |
| 24 | + if (next == 0) break; |
| 25 | + if (curr == next) { |
| 26 | + count++; |
| 27 | + longest = Math.max(longest, count); |
| 28 | + if (count == longest) { |
| 29 | + value = curr; |
| 30 | + longestStartIndex = startIndex; |
| 31 | + } |
| 32 | + } else { |
| 33 | + startIndex = i + 1; |
| 34 | + count = 1; |
| 35 | + } |
| 36 | + |
| 37 | + } |
| 38 | + System.out.println("The longest same number sequence starts at index " + longestStartIndex + |
| 39 | + " with " + longest + " values " + "of " + value); |
| 40 | + |
| 41 | + } |
| 42 | + |
| 43 | + public static void main(String[] args) { |
| 44 | + Scanner input = new Scanner(System.in); |
| 45 | + System.out.println("Enter a series of numbers ending with 0:"); |
| 46 | + String[] tokens = input.nextLine().split("\\s+"); |
| 47 | + new Exercise22_05().findSubsequence(tokens); |
| 48 | + |
| 49 | + input.close(); |
| 50 | + |
| 51 | + } |
| 52 | +} |
0 commit comments