字符串的问题(strstr和strncpy 水题)

链接:https://ac.nowcoder.com/acm/problem/15165
来源:牛客网


有一个字符串 让你找到这个字符串 S 里面的子串T 这个子串 T 必须满足即使这个串的前缀 也是这个
串的后缀 并且 在字符串中也出现过一次的(提示 要求满足前后缀的同时也要在字符串中出现一次 只是前后缀可不行 输出最长满足要求字符串)

具体思路:

strstr函数是判断是不是子串的,返回的是一个指针。

strncpy是用来截取字符串的。

strncy包含三个参数第一个参数是要赋值的字符串,第二个参数是要从这个字符串的哪个位置开始赋值,第三个参数是要赋值的长度。

我们每一次选取前缀,然后选取长度相同的后缀,判断前缀和后缀是不是相等的。然后判断这个字符串除了第一个和最后一个字符的话,会不会包含当前的前缀。然后从合法的值里面选取一个

最大的就可以了。

AC代码:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 # define inf 0x3f3f3f3f
 4 # define ll long long
 5 const ll mod = 998244353;
 6 const int maxn = 1e6+100;
 7 char str[maxn];
 8 char tmp1[maxn],tmp2[maxn],tmp3[maxn];
 9 int main(){
10     scanf("%s",str);
11     int len=strlen(str);
12     int ans=-1;
13     if(len==1)ans=-1;
14     else {
15     for(int i=0; i<len; i++)
16     {
17         strncpy(tmp1,str,i+1);
18         strncpy(tmp2,str+len-1-i,i+1);
19         strncpy(tmp3,str+1,len-2);
20       //  cout<<tmp1<<" "<<tmp2<<" "<<tmp3<<endl;
21         char *tmp=strstr(tmp3,tmp1);
22         if(strcmp(tmp1,tmp2)==0&&tmp!=NULL)
23             ans=max(ans,i+1);
24     }
25     }
26     if(ans==-1)
27         printf("Just a legend
");
28     else
29     {
30         for(int i=0; i<ans; i++)
31         {
32             printf("%c",str[i]);
33         }
34         printf("
");
35     }
36     return 0;
37 }
原文地址:https://www.cnblogs.com/letlifestop/p/10913281.html