Java实现 LeetCode 389 找不同

389. 找不同

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

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

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

示例:

输入:
s = “abcd”
t = “abcde”

输出:
e

解释:
‘e’ 是那个被添加的字母。

class Solution {
    //     public char findTheDifference(String s, String t) {
    //     char res = t.charAt(t.length()-1);
    //     for(int i=0; i<s.length(); i++){
    //         res ^= s.charAt(i);
    //         res ^= t.charAt(i);
    //     }
    //     return res;
    // }
     public char findTheDifference(String s, String t) {
        char[] ss = s.toCharArray();
        char[] tt = t.toCharArray();
        char res = tt[tt.length - 1];
        for(int i=0; i<ss.length; i++){
            res += tt[i] - ss[i];
        }
        return res;
    }
}
发布了1501 篇原创文章 · 获赞 2万+ · 访问量 191万+

猜你喜欢

转载自blog.csdn.net/a1439775520/article/details/104819000