名字缩写(暴力)

题目描述
Noname老师有一个班的学生名字要写,但是他太懒了,想少写几个字母。很快他发现这是可行的,例如下面的学生名单:
Davidson
Davis
Dixon
Smith
可以缩写为
David
Davis
Di
S
David 指明Davidson外,不可能是其他三位同学名字的前缀。S仅能代表Smith。在确保能无歧义指明同学的前提下,Noname老师总是希望使用最少的字母。

输入
给定一系列名字,每个名字一行(不超过100行),名字仅含英文字母,名字长度不超过40,这些名字按字母升序排列, 任意两个名字不相同而且一个名字不会正好是另一个名字的前缀。

输出
每行输入对应一行输出,内容为空格分开原来的名字和缩写后的名字。

样例输入
Adams
Andersen
Anderson
Carson
Carter
Carville
Cooper
Coply
Smith
Smythe
Sorensen
Sorenson
Wynn

样例输出
Adams Ad
Andersen Anderse
Anderson Anderso
Carson Cars
Carter Cart
Carville Carv
Cooper Coo
Coply Cop
Smith Smi
Smythe Smy
Sorensen Sorense
Sorenson Sorenso
Wynn W

思路:暴力搜索,三重循环,第一层是每一个的,第二层是长度,第三层是判断

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
char name[110][50];
char na[110][50];
char str1[50], str2[50];
void scopy(int x, int y, char s[])
{
    for(int i=0; i<=x; i++)
        s[i] = name[y][i];
    s[x+1] = '\0';
}

int main()
{
    int k=0;
    while(scanf("%s",name[k++]) != EOF);
    int i,j,l;
    for(i=0; i < k; i++)
    {
        int flag = 0;
        int len = strlen(name[i]);
        for(j=0; j<len ; j++)
        {
            scopy(j,i, str1);
            for(l=0; l<k; l++)
            {
                if(i == l)
                    continue;
                else
                {
                    scopy(j,l,str2);
                    if(!strcmp(str1,str2))
                    {
                        flag = 1;
                        break;
                    }
                }
            }
            if(flag)
            {
                flag = 0;
                continue;
            }
            if(l == k)
            {
                strcpy(na[i],str1);
                break;
            }
        }
    }
    for(int i=0; i<k; i++)
        cout << name[i] << " " << na[i] << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值