其他分享
首页 > 其他分享> > 【Leetcode】389. Find the Difference

【Leetcode】389. Find the Difference

作者:互联网

题目地址:

https://leetcode.com/problems/find-the-difference/

给定两个字符串,两个字符串其余字母相同,只有其中一个字符串比另一个多一个字母。求出这个字母。可把char类型视为int,然后根据32位int与异或运算构成阿贝尔群且每个元素阶为222的性质,直接异或一遍即可。相关证明可以参照:https://blog.csdn.net/qq_46105170/article/details/104082406

public class Solution {
    public char findTheDifference(String s, String t) {
        char c = 0;
        for (int i = 0; i < s.length(); i++) {
            c ^= s.charAt(i) ^ t.charAt(i);
        }
        return (char) (c ^ t.charAt(s.length()));
    }
}

时间复杂度O(n)O(n)O(n),空间O(1)O(1)O(1)。

edWard的算法世界 发布了96 篇原创文章 · 获赞 0 · 访问量 1923 私信 关注

标签:charAt,int,字母,char,异或,字符串,389,Difference,Leetcode
来源: https://blog.csdn.net/qq_46105170/article/details/104085763