Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Brute Force string matching.
- *
- * Time Complexity: O(M * N)
- *
- * Space Complexity: O(1)
- *
- * M = Length of haystack string. N = length of fneedle string.
- */
- class Solution1 {
- public int strStr(String haystack, String needle) {
- if (needle.isEmpty()) {
- return 0;
- }
- for (int i = 0; i <= haystack.length() - needle.length(); i++) {
- for (int j = 0; j < needle.length(); j++) {
- if (haystack.charAt(i + j) != needle.charAt(j)) {
- break;
- }
- if (j == needle.length() - 1) {
- return i;
- }
- }
- }
- return -1;
- }
- }
- /**
- * Using KMP Algorithm
- *
- * Time Complexity: O(M + N). O(N) to create lookup table. O(M) to find the
- * needle in haystack.
- *
- * Space Complexity: O(N). This is required to save the lookup table.
- *
- * M = Length of haystack string. N = length of fneedle string.
- */
- class Solution2 {
- public int strStr(String haystack, String needle) {
- if (haystack == null || needle == null) {
- return -1;
- }
- if (needle.length() == 0) {
- return 0;
- }
- if (haystack.length() == 0) {
- return -1;
- }
- int[] table = kmpLookupTable(needle);
- int i = 0;
- int j = 0;
- while (i < haystack.length() && j < needle.length()) {
- if (haystack.charAt(i) == needle.charAt(j)) {
- i++;
- j++;
- } else {
- if (j > 0) {
- j = table[j - 1];
- } else {
- i++;
- }
- }
- }
- if (j == needle.length()) {
- return i - j;
- } else {
- return -1;
- }
- }
- private int[] kmpLookupTable(String s) {
- int[] table = new int[s.length()];
- int i = 1;
- int index = 0;
- while (i < s.length()) {
- if (s.charAt(i) == s.charAt(index)) {
- table[i] = index + 1;
- index++;
- i++;
- } else {
- if (index > 0) {
- index = table[index - 1];
- } else {
- table[i] = 0;
- i++;
- }
- }
- }
- return table;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement