Advertisement
1988coder

796. Rotate String

Jan 6th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.10 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/rotate-string/
  2. /**
  3.  * All rotations of A are contained in A+A
  4.  *
  5.  * Time Complexity: O(N^2)
  6.  *
  7.  * Space Complexity: O(N)
  8.  *
  9.  * N = Length of input string A or B
  10.  */
  11. class Solution1 {
  12.     public boolean rotateString(String A, String B) {
  13.         if (A == null || B == null || A.length() != B.length()) {
  14.             return false;
  15.         }
  16.  
  17.         return (A + A).contains(B);
  18.     }
  19. }
  20.  
  21. /**
  22.  * All rotations of A are contained in A+A. Using KMP for checking contains.
  23.  *
  24.  * Time Complexity: O(N)
  25.  *
  26.  * Space Complexity: O(N)
  27.  *
  28.  * N = Length of input string A or B
  29.  */
  30. class Solution {
  31.     public boolean rotateString(String A, String B) {
  32.         if (A == null || B == null || A.length() != B.length()) {
  33.             return false;
  34.         }
  35.         if (A.length() == 0) {
  36.             return true;
  37.         }
  38.  
  39.         int[] lookupTable = genLookupTable(B);
  40.  
  41.         return contains(A + A, B, lookupTable);
  42.     }
  43.  
  44.     private int[] genLookupTable(String s) {
  45.         int[] table = new int[s.length()];
  46.         int i = 1;
  47.         int index = 0;
  48.         while (i < s.length()) {
  49.             if (s.charAt(i) == s.charAt(index)) {
  50.                 index++;
  51.                 table[i] = index;
  52.                 i++;
  53.             } else {
  54.                 if (index > 0) {
  55.                     index = table[index - 1];
  56.                 } else {
  57.                     i++;
  58.                 }
  59.             }
  60.         }
  61.         return table;
  62.     }
  63.  
  64.     private boolean contains(String haystack, String needle, int[] lookupTable) {
  65.         int i = 0;
  66.         int j = 0;
  67.         while (i < haystack.length() && j < needle.length()) {
  68.             if (haystack.charAt(i) == needle.charAt(j)) {
  69.                 i++;
  70.                 j++;
  71.             } else {
  72.                 if (j > 0) {
  73.                     j = lookupTable[j - 1];
  74.                 } else {
  75.                     i++;
  76.                 }
  77.             }
  78.         }
  79.  
  80.         if (j == needle.length()) {
  81.             return true;
  82.         } else {
  83.             return false;
  84.         }
  85.     }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement