"Programming Thinking and Practice" 1046. String spacing

"Programming Thinking and Practice" 1046. String spacing

topic

insert image description here

train of thought

Through the search of the string, find the position of the first occurrence and the position of the last occurrence, then conduct a classification discussion, and finally compare to get the maximum distance.

The strstr function can be called directly for the first occurrence, and the strrstr function (not included in string.h) is needed for the last occurrence, which can be realized by repeatedly calling the strstr function.

Find the position where s1 and s2 appear for the first time and the last time, and there are four possible situations for performing operations in pairs, and then discuss whether s1 is in front or s2 in front (because the distance must be a positive number),

Finally, compare to get the maximum distance.

the code

#include<stdio.h>
#include<string.h>

char *strrstr(char *dest,char* src)   //dest 目标  src search 搜索 
{
    
    
	if(strstr(dest,src)!=NULL)
	{
    
    
		dest=strstr(dest,src)+strlen(src);   //加上长度后从后面开始接着搜
		strrstr(dest,src);	    //反复调用直到找不到字符串
	} 
	else
	{
    
    
		return dest-strlen(src);   //返回头指针 所以需要减去长度
	}
}

int main()
{
    
    
	int T;
	scanf("%d",&T);
	for(int t=0;t<T;t++)
	{
    
    
		char s1[81],s2[81],s[81];
		scanf("%s",s1);
		scanf("%s",s2);
		scanf("%s",s);
		printf("case #%d:\n",t);
        if(strstr(s,s1)==NULL||strstr(s,s2)==NULL)
        {
    
    
            printf("0\n");
        }
		else
        {
    
    
            int d[4];              
            d[0]=strstr(s,s1)-strstr(s,s2)>0?strstr(s,s1)-strstr(s,s2)-strlen(s2):strstr(s,s2)-strstr(s,s1)-strlen(s1);    //>0表明s2在前,需要减掉s2长度
            d[1]=strrstr(s,s1)-strstr(s,s2)>0?strrstr(s,s1)-strstr(s,s2)-strlen(s2):strstr(s,s2)-strrstr(s,s1)-strlen(s1);
            d[2]=strstr(s,s1)-strrstr(s,s2)>0?strstr(s,s1)-strrstr(s,s2)-strlen(s2):strrstr(s,s2)-strstr(s,s1)-strlen(s1);
            d[3]=strrstr(s,s1)-strrstr(s,s2)>0?strrstr(s,s1)-strrstr(s,s2)-strlen(s2):strrstr(s,s2)-strrstr(s,s1)-strlen(s1);;
            int maxdistance=0;  //最远距离
            for(int i=0;i<4;i++)
            {
    
    
                if(d[i]>maxdistance)
                {
    
    
                    maxdistance=d[i];
                }
            }
            printf("%d\n",maxdistance);
        }		
	} 
	return 0;
} 

Guess you like

Origin blog.csdn.net/boxueyuki/article/details/130496174