題目
請僅編寫出一C語言函數char *maxword(char *s, char *t),該函數的功能是求出字符串s與字符串t的最長公共單詞(這裏,假設兩個字符串均由英文字母和空格字符組成);若找到這樣的公共單詞,函數返回該單詞,否則,函數返回NULL。
例如:若s=“This is C programming text”,t=“This is a text for C programming”,則函數返回“programming”。
要求:
1. 函數中不得設置保存單詞的存儲空間;
2. 給出函數之前請用文字簡要敘述函數的基本思想。
答案
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getMaxLengthStr(char *source,int index,int length,char *target){
int pre=0,len=0;
for(int i=0;i<strlen(target)+1;i++){
int currLen=0;
// 按空格將target字符串切分,每個單子都和t的字符串進行比較
if(target[i]==' ' || target[i]=='\0'){
for(int j=pre;j<i;j++){
if(target[j]==source[index+j-pre]){
currLen++;
}else{
break;
}
}
if(currLen>len){
len=currLen;
}
pre=i+1;
}
}
return len;
}
char * maxword(char *s,char *t){
int minIndex=0,length=0,pre=0;
char *res;
for(int i=0;i<strlen(s)+1;i++){
// 按空格將s字符串切分,每個單子都和t的字符串進行比較
if(s[i]==' ' || s[i]=='\0'){
int tempLen=0;
// i-pre是單詞的長度,如果這個單詞長度小於已檢測的公共單詞的最長長度,就跳過
if(i-pre>length){
tempLen=getMaxLengthStr(s,pre,i-pre,t);
if(tempLen> length){
length=tempLen;
minIndex=pre;
}
}
// 將單詞的起始位置置爲空格的後一位
pre=i+1;
}
}
if(length>0){
res=s+minIndex;
res[length]='\0';
return res;
}else{
return NULL;
}
}
int main(int argc, char *argv[] )
{
char *s=argv[1];
char *t=argv[2];
printf("%s\n",maxword(s,t));
return 0;
}
➜ C gcc temp.c
➜ C ./a.out "this is c programming text" "this is a text for c programming"
programming
➜ C ./a.out "this is c programming text" "this is damon"
this
➜ C ./a.out "this is c programming text" "damon is cool"
is
➜ C ./a.out "this is c programming text" "cool"
c
➜ C ./a.out "this is c programming text" "damon"
(null)
➜ C
請多指教