设计一个算法,在顺序串s中从后向前查找子串t,即求t在s中最后一次出现的位置。
时间: 2024-10-20 17:19:32 浏览: 99
要在一个字符串 `s` 中从后向前查找子串 `t` 的最后一次出现位置,你可以使用滑动窗口或倒序搜索的方法。这里我会演示两种方法:
**方法一:滑动窗口(两指针法)**
这是一种常用的动态规划技巧,我们可以维护两个指针,一个指向子串 `t` 的开始位置,另一个指向 `s` 的当前检查点。
```c
#include <stdio.h>
#include <string.h>
int last_occurrence(const char *s, const char *t) {
int n = strlen(s), m = strlen(t);
if (m > n)
return -1; // 如果子串太长,不可能找到
for (int i = n - m; i >= 0; i--) {
int match = 1;
for (int j = 0; j < m; j++) {
if (s[i + j] != t[j]) {
match = 0;
break;
}
}
if (match)
return i; // 找到了匹配,返回起始位置
}
return -1; // 没有找到匹配
}
int main() {
const char *s = "Hello, world!";
const char *t = "world";
printf("Last occurrence of '%s' in '%s': %d\n", t, s, last_occurrence(s, t));
return 0;
}
```
**方法二:倒序遍历**
如果你不介意空间复杂度稍高,可以直接从字符串末尾开始,逐个字符向前比较,直到找到子串 `t` 或结束查找。
```c
#include <stdio.h>
#include <string.h>
int last_occurrence(const char *s, const char *t) {
int n = strlen(s), m = strlen(t);
for (int i = n - 1; i >= m - 1; i--) { // 从后往前,每次检查一位
int match = 1;
for (int j = 0; j < m; j++) {
if (s[i - j] != t[m - j - 1]) {
match = 0;
break;
}
}
if (match)
return i; // 找到了匹配,返回起始位置
}
return -1; // 没有找到匹配
}
int main() {
// ... (同上)
}
```
运行这两个程序,你会得到子串 `t` 在 `s` 中最后一次出现的位置。如果有其他问题或需要进一步解释,请告诉我。
阅读全文
相关推荐

















