LintCode ---- 刷题总结

时间:2023-03-09 13:03:54
LintCode ---- 刷题总结

对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1

基本:两重for循环,时间复杂度O(n^2)。

 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) {
//write your code here
if (source == null || target == null) {
return -1;
}
for (int i = 0; i < source.length() - target.length() + 1; i++) {
int j = 0;
for (j = 0; j < target.length(); j++) {
if (source.charAt(i + j) != target.charAt(j)) {
break;
}
}
if (j == target.length()) {
return i;
}
}
return -1;
}
}

高级:Rabin Karp算法,时间复杂度为O(n+m),n为源字符串长度,m为目标字符串长度。该算法时间复杂度与KMP算法一样,但是比KMP简单,不建议使用KMP,不仅写起来麻烦而且容易错。

 public class Solution {
private static int BASE = 1000000;
/**
* @param source a source string
* @param target a target string
* @return an integer as index
*/
public int strStr2(String source, String target) {
// Write your code here
if (source == null || target == null) {
return -1;
}
int m = target.length();
if (m == 0) {
return 0;
}
//31 ^ m
int power = 1;
for (int i = 0; i < m; i++) {
power = (power * 31) % BASE;
}
//targetCode
int targetCode = 0;
for (int i = 0; i < m; i++) {
targetCode = (targetCode * 31 + target.charAt(i)) % BASE;
}
//hashCode
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 (targetCode == hashCode) {
if (source.substring(i - m + 1, i + 1).equals(target)) {
return i - m + 1;
}
}
}
return -1;
}
}