Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3cd2f63

Browse files
Merge pull request HarryDulaney#32 from HarryDulaney/Add_Chapter_22_23_24_25_answers
Add chapter 22 23 24 25 answers
2 parents 88b6e31 + 7981b4a commit 3cd2f63

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

‎ch_22/Exercise22_04.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import java.util.Scanner;
55

66
/**
7-
* (Pattern matching) Write a program that prompts the user to enter two strings
7+
* *22.4 (Pattern matching) Write a program that prompts the user to enter two strings
88
* and tests whether the second string is a substring of the first string. (Don’t use
99
* the indexOf method in the String class.) Analyze the time complexity of
1010
* your algorithm. Here is a sample run of the program:

‎ch_22/Exercise22_05.java‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /