首页 > 代码库 > String LD

String LD

Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u
Submit Status

Description

Stringld (left delete) is a function that gets a string and deletes its leftmost character (for instance Stringld(“acm”) returns “cm”). 

You are given a list of distinct words, and at each step, we apply stringld on every word in the list. Write a program that determines the number of steps that can be applied until at least one of the conditions become true: 

1) A word becomes empty string, or 
2) a duplicate word is generated. 

For example, having the list of words aab, abac, and caac, applying the function on the input for the first time results in ab, bac, and aac. For the second time, we get b, ac, and ac. Since in the second step, we have two ac strings, the condition 2 is true, and the output of your program should be 1. Note that we do not count the last step that has resulted in duplicate string. More examples are found in the sample input and output section.

Input

There are multiple test cases in the input. The first line of each test case is n (1 <= n <= 100), the number of words. 
Each of the next n lines contains a string of at most 100 lower case characters. 
The input terminates with a line containing 0.

Output

For each test case, write a single line containing the maximum number of stringld we can call.

Sample Input

4aabaaacabaabcddcba3aaabbbbccccc0

Sample Output

12

 

 

方法点击,由于对字符串从左边删除字符时间复杂度比较大,虽然本题的数据规模不是很大,可以在存储的时候将字符串逆置,然后再进行字符串操作,这里为了减少时间复杂度,额外使用了数组来保存记录字符串的长度信息。
代码如下:
#include<stdio.h>#include<string.h>int n;char value[101][101];int len[101];/*保存字符串的长度*/char cache[101];int main(){    int i,j,k,cnt;    while(~scanf("%d",&n))    {        if(n==0)           break;        cnt=0;        for(i=0;i<n;i++)           len[i]=0;        for(i=0;i<n;i++)        {            scanf("%s",cache);            len[i]=strlen(cache);            for(j=0;j<len[i];j++)/*实现字符串的逆序存储*/            {                value[i][j]=cache[len[i]-j-1];            }            value[i][len[i]]=\0;        }        while(1)        {            cnt++;            for(i=0;i<n;i++)/*每个字符串删除一个字符*/            {                len[i]--;                value[i][len[i]]=\0;            }            for(i=0;i<n;i++)            {                if(len[i]==0)                    goto next;/*有字符串为空串*/                                    for(k=0;k<n;k++)                    for(j=k+1;j<n;j++)                        if(len[k]==len[j])/*减少不必要的字符串*/                        {                            if(strcmp(value[k],value[j])==0)                                goto next;                        }            }        }next:         printf("%d\n",--cnt);    }    return 0;}