|
| 1 | +package ch_22; |
| 2 | + |
| 3 | + |
| 4 | +import java.util.Scanner; |
| 5 | + |
| 6 | +/** |
| 7 | + * (Pattern matching) Write a program that prompts the user to enter two strings |
| 8 | + * and tests whether the second string is a substring of the first string. (Don’t use |
| 9 | + * the indexOf method in the String class.) Analyze the time complexity of |
| 10 | + * your algorithm. Here is a sample run of the program: |
| 11 | + * <p> |
| 12 | + * Enter a string s1: Mississippi |
| 13 | + * Enter a string s2: sip |
| 14 | + * matched at index 6 |
| 15 | + * <p> |
| 16 | + * __________________________________________________________________________________________ |
| 17 | + * ----------------------------- Time Complexity Analysis ----------------------------------- |
| 18 | + * __________________________________________________________________________________________ |
| 19 | + * Time complexity is: O(n) (Linear Time) |
| 20 | + * <p> |
| 21 | + * If s1.length is 100 and s2.length is 4: |
| 22 | + * Worst case is that the loop will execute over all values of s1 |
| 23 | + * <p> |
| 24 | + * T(n) = 100 * (s1 String loop) = O(n) |
| 25 | + * <p> |
| 26 | + * So, Time complexity is O(n) because |
| 27 | + * as the length of the input grows, the time will increase at a linear rate |
| 28 | + * based on the size of s1. |
| 29 | + * The size of s2 is not relevant to time complexity because we iterate based on the length of s1. |
| 30 | + */ |
| 31 | +public class Exercise22_04 { |
| 32 | + public static void main(String[] args) { |
| 33 | + Scanner scanner = new Scanner(System.in); |
| 34 | + System.out.print("Enter a string s1: "); |
| 35 | + String s1 = scanner.nextLine(); |
| 36 | + |
| 37 | + System.out.print("Enter a string s2: "); |
| 38 | + String s2 = scanner.nextLine(); |
| 39 | + int result = new Exercise22_04().indexOfSubstring(s1, s2); |
| 40 | + if (result == -1) { |
| 41 | + System.out.println("s2 is not a substring of s1..."); |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + System.out.println("matched at index " + result); |
| 46 | + scanner.close(); |
| 47 | + } |
| 48 | + |
| 49 | + private int indexOfSubstring(String s1, String s2) { |
| 50 | + int index = 0; |
| 51 | + int matchLength = s2.length(); |
| 52 | + char s2Start = s2.charAt(0); |
| 53 | + while (index < (s1.length() - matchLength)) { |
| 54 | + /* Try to match first char in s2 with char at next index */ |
| 55 | + if (s1.charAt(index) == s2Start) { |
| 56 | + String s1Sub = s1.substring(index, index + matchLength); |
| 57 | + if (s1Sub.equals(s2)) { |
| 58 | + return index; |
| 59 | + } |
| 60 | + } |
| 61 | + index++; |
| 62 | + } |
| 63 | + return -1; |
| 64 | + } |
| 65 | +} |
0 commit comments