Leetcode 389 Find the Difference
Posted 琴影
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 389 Find the Difference相关的知识,希望对你有一定的参考价值。
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.
Example:
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation:
‘e‘ is the letter that was added.
题目大意:
给定两个字符串s和t,都只包含小写字母。
字符串t由字符串s打乱顺序并且额外在随机位置添加一个字母组成。
寻找t中新增的那个字母。
测试用例如题目描述。
方法一:利用Hash表,
1 char findTheDifference(string s, string t) { 2 int a[26] = {0}, lens = s.length(), lent = t.length(), i; 3 for(i = 0; i < lens; i++) 4 a[s[i] - ‘a‘]++; 5 for(i = 0; i < lent; i++) 6 if(a[t[i] - ‘a‘] <= 0) 7 break; 8 else 9 a[t[i] - ‘a‘]--; 10 return t[i]; 11 }
方法二:两个字符串加起来只有一个字符时单独的。。利用异或运算
1 char findTheDifference(string s, string t) { 2 int ans = 0, i, lens = s.length(), lent = t.length(); 3 for(i = 0; i < lens; i++) 4 ans ^= (s[i] - ‘a‘); 5 for(i = 0; i < lent; i++) 6 ans ^= (t[i] - ‘a‘); 7 return ‘a‘ + ans; 8 }
以上是关于Leetcode 389 Find the Difference的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 389. Find the Difference
LeetCode_389. Find the Difference
leetcode No389. Find the Difference
leetcode No389. Find the Difference