题目描述:
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中新增的那个字母。
测试用例如题目描述。
解题思路:
分别统计s与t的字母个数,然后比对即可。若使用Python解题,可以使用collections.Counter。
Python代码:
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
ds = collections.Counter(s)
dt = collections.Counter(t)
return (dt - ds).keys().pop()
另一种解法,利用异或运算。
Java代码:
public class Solution {
public char findTheDifference(String s, String t) {
char ans = 0;
for (int i = 0; i < s.length(); i++) {
ans ^= s.charAt(i);
}
for (int i = 0; i < t.length(); i++) {
ans ^= t.charAt(i);
}
return ans;
}
}
本文链接:http://bookshadow.com/weblog/2016/08/28/leetcode-find-the-difference/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。