Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // LeetCode URL: https://leetcode.com/problems/repeated-string-match/
- /**
- * Time Complexity: O((A + B) * B)
- *
- * A+B = Length of the new string in stringbuilder.
- *
- * Space Complexity: O(A + B)
- */
- class Solution1 {
- public int repeatedStringMatch(String A, String B) {
- if (A == null || B == null) {
- return -1;
- }
- if (B.length() == 0 || B.equals(A)) {
- return 1;
- }
- if (A.length() == 0) {
- return -1;
- }
- int count = 0;
- StringBuilder sb = new StringBuilder();
- while (sb.length() < B.length()) {
- sb.append(A);
- count++;
- }
- if (sb.indexOf(B) >= 0) {
- return count;
- }
- sb.append(A);
- count++;
- if (sb.indexOf(B) >= 0) {
- return count;
- }
- return -1;
- }
- }
- /**
- * Using KMP for string contains.
- *
- * Time Complexity: O((A + B) + B)
- *
- * A+B = Length of the new string in stringbuilder.
- *
- * Space Complexity: O(A + B)
- */
- class Solution2 {
- public int repeatedStringMatch(String A, String B) {
- if (A == null || B == null) {
- return -1;
- }
- if (B.length() == 0 || A.equals(B)) {
- return 1;
- }
- if (A.length() == 0) {
- return -1;
- }
- int count = 0;
- StringBuilder sb = new StringBuilder();
- while (sb.length() < B.length()) {
- sb.append(A);
- count++;
- }
- int[] lookupTable = kmpLookupTable(B);
- if (contains(sb.toString(), B, lookupTable)) {
- return count;
- }
- sb.append(A);
- count++;
- if (contains(sb.toString(), B, lookupTable)) {
- return count;
- }
- 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)) {
- index++;
- table[i] = index;
- i++;
- } else {
- if (index > 0) {
- index = table[index - 1];
- } else {
- i++;
- }
- }
- }
- return table;
- }
- private boolean contains(String haystack, String needle, int[] table) {
- 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 true;
- } else {
- return false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement