(字符)串
- 串是一个特殊的线性表,其数据元素全是单个元素,也称字符串:“abcd112_!”
- 长度为零的串里什么都没有,叫空串:“”
- 全由空格组成的串叫空格串,空格也是字符,空格串≠空串:“ ”或“_ _”(_表示空格)
回文串
- 长度为L的字符串的索引范围:[1,L]或[0,L - 1]
- 回文:如“上海自来水来自海上”
- 索引从0开始:s[i] == s[L - i - 1]
- 索引从1开始:s[i] == s[L - i + 1]
字符串匹配
- 给定一个主串s,和一个模式串t,返回t首次在s中出现的位置,若从未出现则返回-1
主串 | 模式串 | 匹配结果 |
---|
aabbccd | bbc | 3 |
kkaakk | kk | 1 |
happy | happyy | -1 |
python | | 1 |
python | python | 1 |
python | abc | -1 |
字符串匹配问题的暴力求解:BF算法
- 给定一个主串s,和一个模式串t,返回t首次在s中出现的位置,若从未出现则返回-1
- 首先判断s的长度大于等于t,否则直接返回-1
- 逐一选择s中的位置i
- 若s[i : L] >= t的长度,则从s[i]开始与t进行逐字符比对
- 匹配失效则回溯到i + 1从t的首字符重新开始
- 时间复杂度O(m * n)
字符串匹配KMP算法
- 暴力求解的BF算法效率为什么低?
- KMP算法是一种利用提前计算部分匹配前缀表来避免回溯的算法
- 提前计算模式串t的next数组
- 匹配过程中发生失效时,直接根据next数组滑动模式串,无需回溯
数据结构KMP算法配图详解(超详细)
代码实现(BF----串匹配)
#include <stdio.h>
#include <string.h>
int BFMatch(const char *s, const char *t);
int BF_Match(const char *s, const char *t, int pos);
int main()
{
char *s = "appleapp", *t = "app";
printf("match(s, t):\t%d\n", BFMatch(s, t));
printf("match(s, t, 2):\t%d\n", BF_Match(s, t, 2));
return 0;
}
int BFMatch(const char *s, const char *t)
{
int m = strlen(s), n = strlen(t);
int i = 0, j = 0;
while (i < m && j < n)
{
if (s[i] == t[j])
{
i++;
j++;
}
else
{
i = i - j + 1;
j = 0;
}
}
if (j == n)
{
return i - n;
}
return -1;
}
int BF_Match(const char *s, const char *t, int pos)
{
int m = strlen(s), n = strlen(t);
int i = pos, j = 0;
while (i < m && j < n)
{
if (s[i] == t[j])
{
i++;
j++;
}
else
{
i = i - j + 1;
j = 0;
}
}
if (j == n)
{
return i - n;
}
return -1;
}