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;
  
}
相关推荐
Escalating_xu9 小时前
【C 语言】深入理解指针(5):sizeof、strlen、数组名语义与指针笔试题全解析
java·c语言·开发语言
Code_Solitude9 小时前
c语言:递归
java·c语言·算法
万年咸鱼10 小时前
解决C语言的内存释放机制
java·c语言·python
老王爱玩车11 小时前
自定义类型:结构体
c语言·开发语言·学习
Logic10113 小时前
C语言/数据结构字符串题解:最短循环节——找出能重复构成原串的最短基础子串
c语言·数据结构·字符串·枚举·时间复杂度·算法题·kmp优化
我就是不信13 小时前
CuTest:轻量级 C 语言单元测试框架实战指南
c语言·单元测试·log4j
Gust of wind14 小时前
串与KMP模式匹配:存储结构、基本操作、next数组手算
c语言·数据结构·后端·算法
Navigator_Z14 小时前
LeetCode //C - 1283. Find the Smallest Divisor Given a Threshold
c语言·算法·leetcode
今夜有雨.16 小时前
图像运算、掩膜/ROI 与绘制交互
c语言·数据结构·c++·qt·算法·计算机视觉
知识分享小能手16 小时前
C学习教程,从入门到精通,C语言概述 —— 知识点详解(1)
c语言·开发语言·学习