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)