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语言中的局部跳转以及全局跳转
android·c语言·开发语言
banjin6 小时前
AI驱动TDSQL-C Serverless 数据库技术实战营-ai学生选课系统数据分析
c语言·人工智能·serverless
DdddJMs__1356 小时前
C语言 | Leetcode C语言题解之第413题等差数列划分
c语言·leetcode·题解
轩轶子6 小时前
【C-项目】网盘(一期,无限进程版)
服务器·c语言·网络
0224号比邻星6 小时前
[C语言]第十节 函数栈帧的创建和销毁一基础知识到高级技巧的全景探索
c语言·开发语言
QXH2000007 小时前
Leetcode—环形链表||
c语言·数据结构·算法·leetcode·链表
爱编程的小新☆11 小时前
C语言内存函数
c语言·开发语言·学习
snowful world12 小时前
vs2022链表的创建和打印(c语言版)
c语言·数据结构·链表
小周的C语言学习笔记13 小时前
鹏哥C语言33---循环语句 for
c语言·c++·算法
LaoWaiHang14 小时前
C语言从头学60——学习头文件math.h(三)
c语言