Skip to content

Add chapter 22 23 24 25 answers #32

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 7, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ch_22/Exercise22_04.java
Original file line number Diff line number Diff line change
@@ -4,7 +4,7 @@
import java.util.Scanner;

/**
* (Pattern matching) Write a program that prompts the user to enter two strings
* *22.4 (Pattern matching) Write a program that prompts the user to enter two strings
* and tests whether the second string is a substring of the first string. (Don’t use
* the indexOf method in the String class.) Analyze the time complexity of
* your algorithm. Here is a sample run of the program:
52 changes: 52 additions & 0 deletions ch_22/Exercise22_05.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package ch_22;

import java.util.Scanner;

/**
* 22.5 (Same-number subsequence) Write an O(n) program that prompts the user to
* enter a sequence of integers ending with 0 and finds the longest subsequence
* with the same number. Here is a sample run of the program:
* Enter a series of numbers ending with 0:
* 2 4 4 8 8 8 8 2 4 4 0
* The longest same number sequence starts at index 3 with 4 values of 8
*/
public class Exercise22_05 {
private void findSubsequence(String[] tokens) {
int longest = 0;
int longestStartIndex = 0;
int count = 1;
int value = 0;
int startIndex = 0;

for (int i = 0; i < tokens.length - 1; i++) {
int curr = Integer.parseInt(tokens[i]);
int next = Integer.parseInt(tokens[i + 1]);
if (next == 0) break;
if (curr == next) {
count++;
longest = Math.max(longest, count);
if (count == longest) {
value = curr;
longestStartIndex = startIndex;
}
} else {
startIndex = i + 1;
count = 1;
}

}
System.out.println("The longest same number sequence starts at index " + longestStartIndex +
" with " + longest + " values " + "of " + value);

}

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a series of numbers ending with 0:");
String[] tokens = input.nextLine().split("\\s+");
new Exercise22_05().findSubsequence(tokens);

input.close();

}
}