Advertisement
1988coder

459. Repeated Substring Pattern

Jan 4th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.97 KB | None | 0 0
  1. /**
  2.  * String Manipulations
  3.  *
  4.  * Refer:
  5.  * https://leetcode.com/problems/repeated-substring-pattern/discuss/94334/Easy-python-solution-with-explaination
  6.  *
  7.  * Time Complexity: O(N^2)
  8.  *
  9.  * Space Complexity: O(N)
  10.  *
  11.  * N = Length of the input string.
  12.  */
  13. class Solution1 {
  14.     public boolean repeatedSubstringPattern(String s) {
  15.         if (s == null || s.length() < 2) {
  16.             return false;
  17.         }
  18.  
  19.         String newS = s.substring(1) + s.substring(0, s.length() - 1);
  20.         return newS.contains(s);
  21.     }
  22. }
  23.  
  24. /**
  25.  * String Searching using KMP
  26.  *
  27.  * Refer: 1)
  28.  * https://leetcode.com/problems/repeated-substring-pattern/discuss/94397/C++-O(n)-using-KMP-32ms-8-lines-of-code-with-brief-explanation.
  29.  * 2)
  30.  * https://leetcode.com/problems/repeated-substring-pattern/discuss/94397/C++-O(n)-using-KMP-32ms-8-lines-of-code-with-brief-explanation./98921
  31.  *
  32.  * Time Complexity: O(N)
  33.  *
  34.  * Space Complexity: O(N)
  35.  *
  36.  * N = Length of the input string.
  37.  */
  38. class Solution {
  39.     public boolean repeatedSubstringPattern(String s) {
  40.         if (s == null || s.length() < 2) {
  41.             return false;
  42.         }
  43.  
  44.         // lps indicates longest proper prefix which is also suffix
  45.         int[] lps = kmpLookupTable(s);
  46.         int len = s.length();
  47.  
  48.         if (lps[len - 1] != 0 && len % (len - lps[len - 1]) == 0) {
  49.             return true;
  50.         } else {
  51.             return false;
  52.         }
  53.     }
  54.  
  55.     private int[] kmpLookupTable(String s) {
  56.         int[] lps = new int[s.length()];
  57.         int i = 1;
  58.         int index = 0;
  59.         while (i < s.length()) {
  60.             if (s.charAt(i) == s.charAt(index)) {
  61.                 lps[i] = index + 1;
  62.                 index++;
  63.                 i++;
  64.             } else {
  65.                 if (index > 0) {
  66.                     index = lps[index - 1];
  67.                 } else {
  68.                     lps[i] = 0;
  69.                     i++;
  70.                 }
  71.             }
  72.         }
  73.         return lps;
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement