Substrings
| Time Limit: 1000MS |
|
Memory Limit: 10000K |
| Total Submissions: 9527 |
|
Accepted: 3272 |
Description
You are given a number of case-sensitive strings of alphabetic characters, find the largest string X, such that either X, or its inverse can be found as a substring of any of the given strings.
Input
The first line of the input contains a single integer t (1 <= t <= 10), the number of test cases, followed by the input data for each test case. The first line of each test case contains a single integer n (1 <= n <= 100), the number of given strings, followed by n lines, each representing one string of minimum length 1 and maximum length 100. There is no extra white space before and after a string.
Output
There should be one line per test case containing the length of the largest string found.
Sample Input
23ABCDBCDFFBRCD2roseorchid
Sample Output
22
Source
Tehran 2002 Preliminary注意:(1)函數原型:extern char *strstr(char *str1, char *str2); 功能:找出str2字串在str1字串中第一次出現的位置(不包括str2的串結束符)。判斷一個子串是否在一個字串中出現(2)原型:char *strcpy(char *dest, char *src); 功能:把src所指由'\0'結束的字串複製到dest所指的數組中。 ( 3) 原型:char * strncpy(char *dest, char *src, size_t n); 功能:將字串src中最多n個字元複製到字元數組dest中(它並不像strcpy一樣只有遇到NULL才停止複製,而是多了一個條件停止,就是說如果複製到第n個字元還未遇到NULL,也一樣停止),返回指向dest的指標。
(4) strlen(char *str) 計算c風格字串的長度。
(5)題意解析: a) 這裡首先從所有的字串中找出最短的那個字串作為源字串。 b) 然後按照從長到短的枚舉方法一個一個的尋找是否其他的字串是否均含有該源字串的子字串。這裡藉助於庫函數strstr c) 遍曆方法,首先是整個源字串,然後是源字串長度減少1的所有字串,然後是減少2的所有字串,如果找到就跳出來輸出。(6)另外注意的是這裡還要求了也可以是某個字串的翻轉字串也可以。
#include <stdio.h>#include <string.h>int main(){ char string[105][105],str[105],pos[105],inv[105]; int i,j,t,n,min_len,index; int flag; scanf("%d",&t); while(t--) { scanf("%d",&n); min_len = 105; for(i = 0; i < n; i++) { scanf("%s",string[i]); //找到最短的字串 if(strlen(string[i])<min_len) { min_len = strlen(string[i]); index = i; } } int len; len = min_len; strcpy(str,string[index]);//將字串拷貝出來 while(len>0) { flag = 0; for(i = 0; i <= min_len-len;i++) { flag = 1;//標記為符合 strncpy(pos,str+i,len);//正向字串 for(j = 0;j<len;j++) inv[j] = pos[len-j-1];//逆向字串 pos[len] = inv[len] ='\0'; for(j = 0;j<n;j++) { /** 包含檔案:string.h 函數名: strstr 函數原型:extern char *strstr(char *str1, char *str2); 功能:找出str2字串在str1字串中第一次出現的位置(不包括str2的串結束符)。 */ if(strstr(string[j],pos)==NULL&&strstr(string[j],inv)==NULL) { flag = 0;//該字串不符合 break; } } if(flag)break;//符合則說明該字串在每個字串中都有,若沒找到繼續迴圈 } if(flag)break;//同上 len--; } printf("%d\n",len); } return 0;}