判断输入的单词能否拼接

给出一组单词,判断是否可以将单词排序,使得每个单词的第一个字母和前一个单词的最后一个字母相同。

 输入:

每个测试数据的第一行为整数N(1<=N<=10000),接下来的N 行,每行为一个单词,每个单词都只包含小写字母并且最多包含100 个字符。

输出:

如果不能将单词序列重组以满足要求,则输出一行”Impossible”,否则输出”Possible”。

 输入样例:

2
ok
ok
2
ok
ko

输出样例:

Impossible
Possible

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include < string.h>
  4 
  5  // 返回单词最后一个字符。
  6  char endOfString( char s[])
  7 {
  8      int i;
  9 
 10      for(i= 0; s[i+ 1]!= ' \0 '; i++)
 11         ;
 12 
 13      return s[i];
 14 }
 15 
 16  // 返回单词第一个字符
 17  char firstOfWord( char s[])
 18 {
 19      return s[ 0];
 20 }
 21 
 22  // 打印所有的单词
 23  /* void print(char temp[][100],int N)
 24  {
 25      int i;
 26      for(i=0; i<N; i++)
 27          printf("%s\n",temp[i]);
 28  } */
 29 
 30  // 查看是不是可以拼接,可则返回1,否则返回0
 31  int check( char temp[][ 100], int N)
 32 {
 33      int i,j,count= 0,flag_pos= 1,count_N= 1;
 34      char head,end;
 35 
 36     head = firstOfWord(temp[ 0]);
 37     end = endOfString(temp[ 0]);
 38     strcpy(temp[ 0], "");
 39 
 40      for(j= 1; j<N; j++)
 41     {
 42         count= 0;
 43          for(i= 1; i<N; i++)
 44         {
 45              if(strcmp(temp[i], "")== 0)
 46                  continue;
 47              else  if(firstOfWord(temp[i])==end)
 48             {
 49                 end = endOfString(temp[i]);
 50                 strcpy(temp[i], "");
 51                 count ++;
 52                 count_N++;
 53             }
 54              else  if(endOfString(temp[i])==head)
 55             {
 56                 head = firstOfWord(temp[i]);
 57                 count++;
 58                 strcpy(temp[i], "");
 59                 count_N++;
 60             }
 61              else
 62              continue;
 63         }
 64 
 65          if(count== 0)
 66         {
 67             flag_pos= 0;
 68              break;
 69         }
 70 
 71          if(count_N==N)
 72          break;
 73 
 74     }
 75      return flag_pos;
 76 }
 77 
 78  int main()
 79 {
 80      int N,flag_pos,i;
 81      char word[ 1000][ 100];
 82 
 83      // printf("please input;\n");
 84      scanf( " %d ",&N);
 85      for(i= 0; i<N; i++)
 86     {
 87         scanf( " %s ",word[i]);
 88     }
 89 
 90     flag_pos = check(word,N);
 91      if(flag_pos== 0)
 92     printf( " Impossible\n ");
 93      else
 94     printf( " Possible\n ");
 95 
 96      // print(word,N);
 97       // printf("%s\n",word[0]);
 98       // printf("The end of the word is %c\n",endOfString(word[0]));
 99       // printf("The first of the word is %c\n",firstOfWord(word[0]));
100 
101      return  0;
102 }

 

转载于:https://www.cnblogs.com/zhengmian/archive/2012/05/12/word_game.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值