Two to One——C语言提高题【7 kyu】

一、原题

链接:Training on Two to One | Codewars

|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Take 2 strings s1 and s2 including only letters from a to z. Return a new sorted string (alphabetical ascending), the longest possible, containing distinct letters - each taken only once - coming from s1 or s2. |

二、解题

1.分析

该题是找出字符串S1、S2共有的字符(重复的仅保留一个),将其按顺序排列,组成新字符串并返回。

2.思路

1)桶思想

遍历s1、s2,使字符与'a'做差,然后使数组a对应下标中的数值+1(即a[i]++),这种"分类"放置,是桶思想的一种应用 。

2)未知错误

若是a[30]不置为0,会发生未知错误,勇士可自行尝试。

复制代码
int a[30]={0},item=0;//需要置空
3)转化、转化、再转化

说实话,这地方处理的有点绕,整体思路还可以,但应该有优化空间,下面就跟觉很绕:

复制代码
 *sum=(char)(i+(int)('a'));//重要

三、Myway

复制代码
#include <stdlib.h>

char *longest (const char *s1, const char *s2)
{
  char * sum=NULL;
  sum=(char *)malloc(sizeof(char)*30);
  char *p;
  p=sum;
// return a nul-terminated, heap-allocated string
	int a[30]={0},item=0;//需要置空
  while(*s1!='\0'){
    item=(int)(*s1 - 'a');
    //printf("%d\n",item);
    a[item]+=1;
    s1++;
  }
  
  while(*s2!='\0'){
    item=(int)(*s2 - 'a');
    a[item]+=1;
    s2++;
  }
  for(int i=0;i<30;i++){
    //printf("%d\n",a[i]);
    if(a[i]>0){
      *sum=(char)(i+(int)('a'));//重要
      //printf("%c\n",*sum);
      sum++;
    }

  }
  *sum='\0';
  return p;
  
}
相关推荐
祈安_2 天前
C语言内存函数
c语言·后端
norlan_jame3 天前
C-PHY与D-PHY差异
c语言·开发语言
czy87874753 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
m0_531237173 天前
C语言-数组练习进阶
c语言·开发语言·算法
Z9fish3 天前
sse哈工大C语言编程练习23
c语言·数据结构·算法
代码无bug抓狂人3 天前
C语言之单词方阵——深搜(很好的深搜例题)
c语言·开发语言·算法·深度优先
CodeJourney_J3 天前
从“Hello World“ 开始 C++
c语言·c++·学习
枫叶丹43 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
with-the-flow3 天前
从数学底层的底层原理来讲 random 的函数是怎么实现的
c语言·python·算法
Sunsets_Red4 天前
P8277 [USACO22OPEN] Up Down Subsequence P 题解
c语言·c++·算法·c#·学习方法·洛谷·信息学竞赛