1,题目大意
给定两个由小写字母构成的字符串s和t,t是由s中的所有字母随机打乱后在任一位置插入一个新字母构成的字符串。请在t中找出新加入的字母。
2,分析
(1)通过计数。用count[26]数组记录26个字母出现的次数,统计s时候做加法,统计t的时候做减法,最后为-1的就是解。(直接访问,很快)
(2)用map计数。和上面一样,只是把数组换成了map。
(3)用异或。把s,t按字符做异或,得到的就是答案。
异或的性质:
a ^ b = b ^ a
a ^ b ^ c = a ^ (b ^ c)
a ^ 0 = a
a ^ a = 0
3,java代码
(1)数组计数
public static char findTheDifference(String s, String t) {
int[] count = new int[26];
for(int i=0;i<s.length();i++) {
count[s.charAt(i) - 'a']++;
}
for(int i=0;i<t.length();i++) {
count[t.charAt(i) - 'a']--;
}
for(int i=0;i<count.length;i++) {
if(count[i] == -1) {
return (char)(i + 'a');
}
}
return 'z';
}
(2)map计数
public static char findTheDifference2(String s, String t) {
HashMap<Character, Integer> count = new HashMap<Character, Integer>();
for(int i=0;i<s.length();i++) {
if(count.get(s.charAt(i)) == null)
count.put(s.charAt(i), 1);
else {
count.put(s.charAt(i), count.get(s.charAt(i))+1);
}
}
for(int i=0;i<t.length();i++) {
if(count.get(t.charAt(i)) == null) {
return t.charAt(i);
}else {
count.put(t.charAt(i), count.get(t.charAt(i))-1);
}
}
for(Character c:count.keySet()) {
if(count.get(c) == -1) {
return c;
}
}
return 'z';
}
(3)异或:很简单,看python代码
4,代码python
(1)数组计数:很快,在90%以上
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
count = [0]*26
for i in s:
count[ord(i) - 97] +=1
for i in t:
count[ord(i) - 97] -=1
return chr(count.index(-1) + 97)
(2)map计数:和java类似
(3)异或:本以为会比数组计数快,可能是异或运算本身耗时,比例67%左右
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
a = 0
for i in s:
a = a ^ ord(i)
for i in t:
a = a ^ ord(i)
return chr(a)
(4)改进异或:异或可能运算本身耗时,试一试用减法代替果然很快,比数组计数还快一点,可以达到95%以上
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
res = ord(t[-1])
for i in xrange(len(s)):
res = res + ord(t[i]) - ord(s[i])
return chr(res)