嚯 第一次做力扣的每日一题
题目
https://leetcode-cn.com/problems/find-the-difference/
方法一:计数
时间复杂度:O(N),其中 N 为字符串的长度。
空间复杂度:O(1)。固定数量26的数组。
class Solution {
public char findTheDifference(String s, String t){
if(s.length()==0)
return t.charAt(0);
int[] count=new int[26];
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
count[c-'a']++;
}
for(int i=0;i<t.length();i++){
char c=t.charAt(i);
if(count[c-'a']==0)
return c;
count[c-'a']--;
}
return 'a';
}
}
方法二:ASCII
对s中的字符求和,对t中的字符求和,他们的差就是结果。
class Solution {
public char findTheDifference(String s, String t) {
int as = 0, at = 0;
for (int i = 0; i < s.length(); ++i) {
as += s.charAt(i);
}
for (int i = 0; i < t.length(); ++i) {
at += t.charAt(i);
}
return (char) (at - as);
}
}
时间复杂度:O(N)
空间复杂度:O(1)
方法三:位运算
如果将两个字符串拼接成一个字符串,则问题转换成求字符串中出现奇数次的字符。类似于「136. 只出现一次的数字」,我们使用位运算的技巧解决本题。
class Solution {
public char findTheDifference(String s, String t) {
int ret = 0;
for (int i = 0; i < s.length(); ++i) {
ret ^= s.charAt(i);
}
for (int i = 0; i < t.length(); ++i) {
ret ^= t.charAt(i);
}
return (char) ret;
}
}
时间复杂度:O(N)
空间复杂度:O(1)