day09:字符串-28. 实现 strStr()、459.重复的子字符串
LeetCode 28. 实现 strStr()
题目链接:
文章讲解:
https://programmercarl.com/0028.%E5%AE%9E%E7%8E%B0strStr.html
视频讲解:
https://www.bilibili.com/video/BV1PD4y1o7nd/
思路和解法:
KMP算法
主要思想:**当出现字符串不匹配时,可以记录一部分之前已经匹配的文本内容,利用这些信息避免从头再去做匹配。**具体的介绍请看文章讲解。
public class Solution {
public int StrStr(string haystack, string needle) {
if (string.IsNullOrEmpty(needle))
{
return 0;
}
int[] prefixTable = BuildPrefixTable(needle);
int i = 0; // 指向haystack的指针
int j = 0; // 指向needle的指针
while (i < haystack.Length)
{
if (haystack[i] == needle[j])
{
i++;
j++;
if (j == needle.Length)
{
return i - j; // 找到匹配,返回起始索引
}
}
else if (j > 0)
{
j = prefixTable[j - 1]; // 部分匹配,利用前缀表跳过部分字符
}
else
{
i++;
}
}
return -1; // 未找到匹配
}
public int[] BuildPrefixTable(string pattern)
{
int[] prefixTable = new int[pattern.Length];
int length = 0;
int i = 1;
while (i < pattern.Length)
{
if (pattern[i] == pattern[length])
{
length++;
prefixTable[i] = length;
i++;
}
else
{
if (length != 0)
{
length = prefixTable[length - 1];
}
else
{
prefixTable[i] = 0;
i++;
}
}
}
return prefixTable;
}
}
LeetCode 459.重复的子字符串
题目链接:
文章讲解:
https://programmercarl.com/0459.%E9%87%8D%E5%A4%8D%E7%9A%84%E5%AD%90%E5%AD%97%E7%AC%A6%E4%B8%B2.html#%E7%AE%97%E6%B3%95%E5%85%AC%E5%BC%80%E8%AF%BE
视频讲解:
https://www.bilibili.com/video/BV1cg41127fw/
思路和解法:
public class Solution {
public bool RepeatedSubstringPattern(string s) {
if (s.Equals("")) return false;
int len = s.Length;
// 原串加个空格(哨兵),使下标从1开始,这样j从0开始,也不用初始化了
s = " " + s;
char[] chars = s.ToCharArray();
int[] next = new int[len + 1];
// 构造 next 数组过程,j从0开始(空格),i从2开始
for (int i = 2, j = 0; i <= len; i++) {
// 匹配不成功,j回到前一位置 next 数组所对应的值
while (j > 0 && chars[i] != chars[j + 1]) j = next[j];
// 匹配成功,j往后移
if (chars[i] == chars[j + 1]) j++;
// 更新 next 数组的值
next[i] = j;
}
// 最后判断是否是重复的子字符串,这里 next[len] 即代表next数组末尾的值
if (next[len] > 0 && len % (len - next[len]) == 0) {
return true;
}
return false;
}
}