Skip to content

Commit de31a21

Browse files
committed
Chap 22, Ex: 02
1 parent add6448 commit de31a21

File tree

2 files changed

+46
-2
lines changed

2 files changed

+46
-2
lines changed

ch_22/Exercise22_01.java

+3-2
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@
1313
* Enter a string: abcabcdgabmnsxy
1414
* abmnsxy
1515
* <p>
16-
* _____________________________________________
16+
* __________________________________________________________________________________________
17+
* ----------------------------- Time Complexity Analysis -----------------------------------
18+
* __________________________________________________________________________________________
1719
* If input string is length 20:
1820
* ---- T(n) = 20 * (input string loop) * (substring loop) = O(n^2) -----
1921
* Time complexity is O(n^2).
@@ -39,7 +41,6 @@ public static void main(String[] args) {
3941
}
4042
}
4143
System.out.println(maxSub);
42-
4344
input.close();
4445
}
4546

ch_22/Exercise22_02.java

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package ch_22;
2+
3+
import java.util.Scanner;
4+
5+
/**
6+
* *22.2 (Maximum increasingly ordered subsequence) Write a program that prompts
7+
* the user to enter a string and displays the maximum increasingly ordered subsequence of characters.
8+
* Analyze the time complexity of your program. Here is a sample run:
9+
* <p>
10+
* Enter a string: Welcome
11+
* Welo
12+
* __________________________________________________________________________________________
13+
* ----------------------------- Time Complexity Analysis -----------------------------------
14+
* __________________________________________________________________________________________
15+
* Linear Growth Rate (Linear Algorithm)
16+
* For example:
17+
* If input string is length 20:
18+
* ---- T(n) = 20 * (input string loop) = O(n) -----
19+
* So, Time complexity is O(n) because
20+
* as the length of the input grows, the time will increase at a linear rate
21+
* based on the size of the input.
22+
* __________________________________________________________________________________________
23+
*/
24+
public class Exercise22_02 {
25+
public static void main(String[] args) {
26+
Scanner in = new Scanner(System.in);
27+
System.out.print("Enter a string: ");
28+
String input = in.next().trim();
29+
String result = "";
30+
char lastSeqChar = input.charAt(0);
31+
/* Loop always executes one time, so growth rate of time is constant as the input string gets larger */
32+
for (int j = 1; j < input.length(); j++) {
33+
if (lastSeqChar < input.charAt(j)) {
34+
result += lastSeqChar + "";
35+
lastSeqChar = input.charAt(j);
36+
}
37+
}
38+
result += lastSeqChar;
39+
System.out.println(result);
40+
41+
in.close();
42+
}
43+
}

0 commit comments

Comments
 (0)