例1:leetcode 28. Implement strStr()
solution-github
Time complexity: O(n^2)
- KMP算法是解決這個算法很標(biāo)準(zhǔn)的方法很洋,要問清楚數(shù)據(jù)量,小數(shù)據(jù)量沒必要用KMP
- 這個題經(jīng)常在電面中出現(xiàn)
- 如果真的問KMP怎么辦,首先概率很低,另外撼班,換一個更簡單的算法Rabin-Karp胆数,跟KMP時間復(fù)雜度一樣
class Solution {
/**
* Returns a index to the first occurrence of target in source,
* or -1 if target is not part of source.
* @param source string to be scanned.
* @param target string containing the sequence of characters to match.
*/
public int strStr(String source, String target){
if(target=="") return 0;
if(source==""||source==null||target==null) return -1;
for(int s = 0; s<source.length(); s++){
int tmp = s;
int t = 0;
while(source.charAt(tmp)==target.charAt(t)){
if(t==target.length()-1) return s;
tmp++;
t++;
if(tmp>source.length()-1) return -1;
}
}
return -1;
}
}
Rabin-Karp算法解決strStr
public class Solution {
public int BASE = 100000;
/**
* @param source a source string
* @param target a target string
* @return an integer as index
*/
public int strStr2(String source, String target) {
if(source == null|| target==null) return -1;
int m = target.length();
if(m ==0) return 0;
int power = 1;
for(int i = 0; i < m; i++){
power = (power*31)%BASE;
}
int targetHash = 0;
for(int i = 0; i < m; i++){
targetHash=(targetHash*31+target.charAt(i))%BASE;
}
int hashCode = 0;
for(int i = 0; i<source.length();i++){
hashCode= (hashCode*31+source.charAt(i))%BASE;
if(i<m-1) continue;
if(i>=m){
hashCode=hashCode-(source.charAt(i-m)*power)%BASE;
if(hashCode<0){
hashCode+=BASE;
}
}
if(hashCode == targetHash){
if(source.substring(i-m+1,i+1).equals(target)){
return i-m+1;
}
}
}
return -1;
}
}
kmp算法完慧,之前知乎看到過一個税手,講的不太清楚蜂筹,這個還不錯http://jakeboxer.com/blog/2009/12/13/the-knuth-morris-pratt-algorithm-in-my-own-words/
該算法推廣到二維,在matrix中找string芦倒,可以看StringMatch2D
tips:
Time Complexity of String.substring()
It was O(1) in older versions of Java. However, this has actually changed started with Java 7. The char[] sharing was eliminated, and the offset and length fields were removed. Now substring() just copies all the characters into a new String.
Ergo, substring is O(n) in Java 7 update 6.