以顺序存储结构表示串,试设计c语言代码一个算法求串s和t的一个最长公共子串
时间: 2024-05-09 12:18:32 浏览: 96
以下是C语言代码实现最长公共子串的算法:
```
#include <stdio.h>
#include <string.h>
void longest_common_substring(char *s, char *t)
{
int s_length = strlen(s);
int t_length = strlen(t);
int max_length = 0, max_index = 0;
int matrix[100][100] = {0};
for (int i = 0; i < s_length; i++) {
for (int j = 0; j < t_length; j++) {
if (s[i] == t[j]) {
if (i == 0 || j == 0) {
matrix[i][j] = 1;
} else {
matrix[i][j] = matrix[i-1][j-1] + 1;
}
if (matrix[i][j] > max_length) {
max_length = matrix[i][j];
max_index = i;
}
}
}
}
printf("最长公共子串为:");
for (int k = max_index - max_length + 1; k <= max_index; k++) {
printf("%c", s[k]);
}
printf("\n");
}
int main(void)
{
char s[100], t[100];
printf("请输入字符串s:");
scanf("%s", s);
printf("请输入字符串t:");
scanf("%s", t);
longest_common_substring(s, t);
return 0;
}
```
以上代码通过动态规划求解两个字符串的最长公共子串,并将结果输出。请注意,此代码只适用于顺序存储结构表示的字符串。
阅读全文
相关推荐
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)