从一个题看python凶残

这几天看python感觉很不适应,刚好有人问一个算法题。我第一思路用c实现一遍,时间复杂度n空间复杂度大点,后想到用python发现python凶残的无语。
编写一个函数,实现的功能是在A字符串中没有出现但是在B字符串中出现,把在B字符串中出现的字符保存到字符串U中,并输出字符串U;例如:A字符串“ADCEF",B字符串“gg”,则字符串U是“gg”

c代码如下:
#include<iostream>
/*
函数功能:查找在A字符串中有而B字符中没,并输出到out中
*/
static void difstr(const char *source,const char *dest,char *out)
{
	if(dest==NULL){*out='\0';return;}
	if(source==NULL){memcpy(out,dest,strlen(dest)+1);return;}
	char hash[256];
	int len1=strlen(source);
	memset(hash,0,sizeof(hash));
	for(int i=0;i<len1;i++)
		hash[source[i]]=1;
	len1=strlen(dest);
	for(int i=0;i<len1;i++)
	{
		if(!hash[dest[i]])
			*out++=dest[i];
	}
	*out='\0';
}

下面函数主要是在空间复杂度上优化,用位图思路
static void difstr1(const char *source,const char *dest,char *out)
{
	if(dest==NULL){*out='\0';return;}
	if(source==NULL){memcpy(out,dest,strlen(dest)+1);return;}
#define LEN(x) x/8
#define LEN1(x) x%8
	char hash[LEN(256)];
	memset(hash,0,sizeof(hash));
	int len1=strlen(source);
#define or(x,n) (x)|=(1<<(n))
	for(int i=0;i<len1;i++)
		or(hash[LEN(source[i])],LEN1(source[i]));
	len1=strlen(dest);
#define getbit(n,pos) (n>>pos)&1
	for(int i=0;i<len1;i++)
	{
		if(!getbit((int)hash[LEN(dest[i])],LEN1(dest[i])))
			*out++=dest[i];
	}
	*out='\0';
}
int main()
{
	char *s="abc";
	char *ss="ad";
	char out[30];
	difstr1(s,ss,out);
	printf("%s",out);
} 



python代码
for x in b:
	if not x in a:
		print(x)


这里没有存储直接打印虽然目前不会写测试python运行时间,但从代码量上看python提高生产力是无可置疑的 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值