题目地址:
https://www.lintcode.com/problem/1266/
给定两个字符串 s s s和 t t t, t t t是 s s s的某个排列,并且在某个位置添加一个字符。求这个字符。
可以用位运算。代码如下:
public class Solution {
/**
* @param s: a string
* @param t: a string
* @return: the letter that was added in t
*/
public char findTheDifference(String s, String t) {
// Write your code here
char res = 0;
for (int i = 0; i < s.length(); i++) {
res ^= s.charAt(i) ^ t.charAt(i);
}
return (char) (res ^ t.charAt(s.length()));
}
}
时间复杂度 O ( l s ) O(l_s) O(ls),空间 O ( 1 ) O(1) O(1)。