Find The Differenc

     *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.
     * eg:
     * Input:
     *      s = "abcd"
     *      t = "abcde"
     * 
     * Output:
     *      e
     *      

     *要读懂题意思,这个题意思就是 在字符串s的随机位置插入一个字符得到字符串t,求插入的字符是哪个

    //利用直接加和减,相同的字符一减一加也抵消了

    private char FindTheDifference(string s, string t)
    {
        char res = (char)0;
        foreach (char c in t)
            res += c;
        foreach (char c in s)
            res -= c;                                      
        return res;
    }
    //利用异或运算(相同为假,不同为真)运算公式: a^b^a=b;
    //利用异或运算(相同为假,不同为真)运算公式: a^b^a=b;
    private char FindTheDifference2(string s, string t)
    {
        char res = (char)0;
        foreach (char c in s)
            res ^= c;
        foreach (char c in t)
            res ^= c;
        return res;
    }



猜你喜欢

转载自blog.csdn.net/wenbooboo/article/details/81034942