|
| 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