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(即ai++),这种"分类"放置,是桶思想的一种应用 。

2)未知错误

若是a30不置为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;
  
}
相关推荐
十月的皮皮27 分钟前
C语言学习笔记20260606- 求月份天数三种写法
c语言·笔记·学习
caimouse1 小时前
Reactos 第 5 章 进程与线程 — 5.8 Windows 的 APC 机制
c语言·windows
努力攻坚操作系统4 小时前
编程语言编译运行机制对比:C / Java / Python
java·c语言·python
学会去珍惜4 小时前
C语言简介
c语言·开发语言
凡人叶枫5 小时前
Effective C++ 条款07:为多态基类声明 virtual 析构函数
linux·c语言·开发语言·c++
matlabgoodboy5 小时前
计算机java程序代写python代码编写c/c++代做qt设计php开发matlab
java·c语言·python
caimouse6 小时前
Reactos 第 5 章 进程与线程 — 5.11 线程本地存储 TLS
c语言·windows
格发许可优化管理系统6 小时前
Mentor许可证使用规定全解析
java·大数据·c语言·开发语言·c++
caimouse8 小时前
Reactos 第 5 章 进程与线程 — 5.12 进程挂靠
c语言·windows
Byte Wizard9 小时前
C语言编译与链接
c语言