【Leetcode】389. Find the Difference

题目地址:

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

给定两个字符串,两个字符串其余字母相同,只有其中一个字符串比另一个多一个字母。求出这个字母。可把char类型视为int,然后根据32位int与异或运算构成阿贝尔群且每个元素阶为 2 2 的性质,直接异或一遍即可。相关证明可以参照: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 ( 1 ) O(1)

发布了96 篇原创文章 · 获赞 0 · 访问量 1826

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/104085763