LeetCode算法题:找不同

给定两个字符串 s 和 t,它们只包含小写字母。

字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。

请找出在 t 中被添加的字母。

示例:

输入:
s = "abcd"
t = "abcde"

输出:
e

解释:
'e' 是那个被添加的字母。
class Solution {
    public char findTheDifference(String s, String t) {
        ArrayList<Character> chars1 = new ArrayList<>();
        ArrayList<Character> chars2 = new ArrayList<>();
        for (int i = 0; i < t.length(); i++) {
            chars1.add(t.charAt(i));
        }

        for (int i = 0; i < s.length(); i++) {
            chars2.add(s.charAt(i));
        }
        Collections.sort(chars1);
        Collections.sort(chars2);

        for (int i = 0; i < chars2.size(); i++) {
            if (chars2.get(i) != chars1.get(i)) return chars1.get(i);

        }
        return chars1.get(chars1.size() - 1);
    }
}
测试结果
输入:
s = "beautifulboy"

// boy移到前加“s”
t = "boysbeautiful"

输出:
s
原文地址:https://www.cnblogs.com/libera11/p/8799257.html