求两个字符串的最长公共字串(连续)
生活随笔
收集整理的這篇文章主要介紹了
求两个字符串的最长公共字串(连续)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述:
輸入兩個字符串,求其的最長的公共的字串,這與最長公共子序列不一樣
輸出兩字符串的最長公共字串
思路一:
從字符串A開始遍歷,同時遍歷字符串A,找到第一個與當前字符串A相同的字符,此時記下當前的pos,并同時遍歷兩字符串,
直到找到兩字符串不相同的字符,記下其長度,與max比較,大則則將相同的子串copy到max_str中
C++實現
?
#include <stdio.h> #include <string.h> char* longest_str(char* one, char* two) {int i=0, j=0, max=0, m=0; //m:record the number of equal charactersint len_one = strlen(one);int len_two = strlen(two);char *max_str = (char*)malloc(len_one+1);memset(max_str, 0, len_one+1); for(i=0; i<len_one; i++){for(j=0; j<len_two; j++){if(one[i]==two[j]) //the first equal character{for(m=0; one[i+m]==two[j+m]; m++); //m equal charactersif(m>max) //compare m and max{max = m;strncpy(max_str, &two[j], m); //copy m charactersmax_str[m]='\0';}}}} return max_str; }?
?
?
總結
以上是生活随笔為你收集整理的求两个字符串的最长公共字串(连续)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android 编程下 java.lan
- 下一篇: 菜鸟学Java(七)——Ajax+Ser