Leetcode[389] Find the Difference

34 篇文章 0 订阅
16 篇文章 0 订阅

Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.

比較笨的方法,通過快速排序,對齊兩個字符串,再一一進行比較

void fast_sort(int start, int end, char *array)
{
	if(start>=end)
		return;
	int pivot=array[start];
	int i=start;
	int j=end;
	while(i<j)
	{
		while(i<j && array[j]>=pivot)
		{
			j--;
		}
			array[i]=array[j];
		while(i<j && array[i]<=pivot)
		{
			i++;
		}
		array[j]=array[i];
	}
	array[i]=pivot;
	fast_sort(start,i-1, array);
	fast_sort(i+1,end,array);
}

char findTheDifference(char* s, char* t)
{
	int len1=strlen(s);
	int len2=strlen(t);

	char *comp1=(char *)malloc(sizeof(char)*strlen(t));
	//char *comp2=(char *)malloc(sizeof(char)*strlen(t));
	memcpy(comp1,t,len2);
	printf("len t:%d,len s:%d\n",strlen(t),strlen(s));
	printf("%s\n",s);
	printf("%s\n",t);
	fast_sort(0,len1-1,s);
	fast_sort(0,len2-1,t);
	printf("%s\n",s);
	printf("%s\n",t);
	
	for(int i=0;i<len1;i++)
	{
		if(s[i]!=t[i])
		{
			if(t[i]==comp1[len2-1]);
				return s[i];
		}
	}
	char ret=t[len2-1];
	//free(comp1);
	//free(comp2);
	printf("%c",ret);
	return ret;
}

可以通過字符串纍加再做減法,但是如果字符串太長,可能會有溢出風險,所以用bit 位操作最爲穩妥
通過bit 位操作

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        c=0
        
        for a in s:
            c =c ^ ord(a)  # cannot use int(), ord() function convert to asii code
         
        for a in t:
            c =c ^ ord(a)
        
        return chr(c)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值