您的位置:首页 > Web前端

leetcode - 389. Find the Difference

2018-02-28 22:16 225 查看
Problem: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.

解释:    字符串t是由s添加加入了一个字符然后打乱形成的字符串,现在要你找出t中添加的字符是什么。

Solve:由于t相对于s只是多了个字符,所以长度也比s多1,运用 ^ 操作符实现,’A‘^'A'=0, 0^'B'='b',除了那个添加的字符,两个字符串其他字符都是一一对应的也就是成对存在的。这样一直使用^就能得到新加的字符。O(n)),AC-8ms)。
public char findTheDifference(String s, String t) {
char re=0;
for (int i = 0; i <s.length() ; i++) {
re^=s.charAt(i)^t.charAt(i);
}
return re^=t.charAt(t.length()-1);
}
后记:讲道理我这个算法的复杂度很低啊,,但运行时间打败40%。。就很奇怪。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: