389. 找不同|每日一题
给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例 1:
输入:s = “abcd”, t = “abcde”
输出:“e”
解释:‘e’ 是那个被添加的字母。
示例 2:
输入:s = “”, t = “y”
输出:“y”
示例 3:
输入:s = “a”, t = “aa”
输出:“a”
示例 4:
输入:s = “ae”, t = “aea”
输出:“a”
自己写的
package 每日一题;
import java.util.Arrays;
/*
* 1、 搜索插入位置(35)
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。
如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
*/
public class a389找不同 {
public static char findTheDifference(String s, String t) {
char res =0;
char[]t1=t.toCharArray();
char []s1=s.toCharArray();
Arrays.sort(t1);
Arrays.sort(s1);
for (int i = 0; i < t1.length-1; i++) {
if(t1[i]!=s1[i]) {
return t1[i];
}
}
return t1[t1.length-1];
}
public static char findTheDifference1(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);
}
public static void main(String[] args) {
System.out.println(findTheDifference("ae","aae"));
}
}
方法二:求和
将字符串所有值累加,两字符串再相减,得出的的值转换为char行,就最终的答案
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);
}
}
方法三:位运算
如果将两个字符串拼接成一个字符串,则问题转换成求字符串中出现奇数次的字符。类似于「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;
}
}
来源:力扣(LeetCode)