Find the Difference

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

Given two stringssandtwhich consist of only lowercase letters.

Stringtis generated by random shuffling stringsand then add one more letter at a random position.

Find the letter that was added int.

Thoughts

和上道题基本一样,只是数据类型换成了char. 我们知道char除了位数比int少之外基本等价int。

Code

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

        for (int i = 0; i < t.length(); i++) {
            res ^= t.charAt(i);
        }

        return res;
    }
}

Analysis

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

Last updated