【问题描述】[困难]
【解答思路】
1. Rabin-Karp 字符串编码(详见总结)
关于为什么哈希值计算乘数为31,说法是,首先31是质数,其次编译器会将31*i 优化为 (i<<5)-i
时间复杂度:O(N^2) 空间复杂度:O(1)
// 本质上就是循环比较前缀与后缀是否相等
// 利用substring equals会超时
// 利用字符串hash值来进行比较,每次也不需要重新计算
// 对于前缀 hash = hash*31 + 新添头字符ch
// 对于后缀 hash = hash + 新添尾字符*31^t (t为后缀长度减1)
// 有几次提交结果是12ms 不知道是什么原因
public String longestPrefix(String s) {int len = s.length();char chars[] = s.toCharArray();int max = 0, iHash = 0, jHash = 0, times = 1;for(int i=1; i<len; i++,times*=31){iHash = iHash*31 + chars[i-1];jHash += chars[len-i]*times;if(iHash==jHash) max = i;}return s.substring(0,max);
}
2. KMP
时间复杂度:O(N) 空间复杂度:O(1)
public String longestPrefix(String s) {int[] maxMatchLens = new int[s.length()];int currentLen = 0;for (int i = 1; i < s.length(); i++) {while (currentLen > 0 && s.charAt(i) != s.charAt(currentLen)) {currentLen = maxMatchLens[currentLen - 1];}if (s.charAt(i) == s.charAt(currentLen)) {currentLen++;}maxMatchLens[i] = currentLen;}return s.substring(0, currentLen);
}
【总结】
1.Rabin-Karp 字符串编码
2.KMP匹配
返回起始坐标 (text里面找pattern)
public String longestPrefix(String s) {int[] maxMatchLens = new int[s.length()];int currentLen = 0;for (int i = 1; i < s.length(); i++) {while (currentLen > 0 && s.charAt(i) != s.charAt(currentLen)) {currentLen = maxMatchLens[currentLen - 1];}if (s.charAt(i) == s.charAt(currentLen)) {currentLen++;}maxMatchLens[i] = currentLen;}return s.substring(0, currentLen);
}private int[] getMaxMatchLens(String pattern) {int[] maxMatchLens = new int[pattern.length()];int currentLen = 0;for (int i = 1; i < pattern.length(); i++) {while (currentLen > 0 && pattern.charAt(i) != pattern.charAt(currentLen)) {currentLen = maxMatchLens[currentLen - 1];}if (pattern.charAt(i) == pattern.charAt(currentLen)) {currentLen++;}maxMatchLens[i] = currentLen;}return maxMatchLens;
}
3. KMP 算法基础知识
转载链接:https://leetcode-cn.com/problems/longest-happy-prefix/solution/ni-zhen-de-li-jie-kmpma-jiao-ni-xun-su-zhang-wo-bi/
转载链接:https://leetcode-cn.com/problems/longest-happy-prefix/solution/zui-chang-kuai-le-qian-zhui-by-leetcode-solution/
参考链接:https://leetcode-cn.com/problems/longest-happy-prefix/solution/javazi-fu-chuan-hash-fu-za-du-on-7ms-zhi-xu-9xing-/
参考链接:https://blog.csdn.net/V_0617/article/details/79114860