Find the Difference

389. Find the Difference

Given two strings s and t which consist of only lowercase letters.

String t is generated by random shuffling string s and then add one more letter at a random position.

Find the letter that was added in t.

 

一開始想的方法只是單純的照字面上做處理,先將字串排序過後,再透過迴圈檢查,若找到不一樣的部分就回傳

public char findTheDifference(String s, String t) {
    char[] charS = s.toCharArray();
    char[] charT = t.toCharArray();

    Arrays.sort(charS);
    Arrays.sort(charT);

    for(int i=0; i<charS.length; i++) {
        if(charS[i] != charT[i]) {
            return charT[i];
        }
    }

    return charT[charT.length - 1];
}

後來想到可以透過 ascii 來比較,將兩個字串的字元轉換成 ascii 數值,兩者的總合相減,就可以得出多的字元 ascii 數值,在將之還原成 character 回傳即可

public char findTheDifference(String s, String t) {
    char[] charS = s.toCharArray();
    char[] charT = t.toCharArray();
    int charNum = 0;

    for(char ch : charT) {
        charNum += (int)ch;
    }

    for(char ch : charS) {
        charNum -= (int)ch;
    }

    return (char)charNum;
}

另外在討論區還有看到透過 XOR 來做比對的,具體原理就是透過相同數值做 xor 會回傳 0,來過濾掉重複的字元 (以下為參考網址)

https://leetcode.com/problems/find-the-difference/discuss/86825/Java-solution-using-bit-manipulation