美文网首页
389. Find the Difference 找不同

389. Find the Difference 找不同

作者: 这就是一个随意的名字 | 来源:发表于2017-07-30 10:31 被阅读0次

    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.
    Example:
    Input:
    s = "abcd"
    t = "abcde"
    Output:
    e
    Explanation:
    'e' is the letter that was added.
    给定只含小写字母的字符串s和t,其中t由s混排并在随机位置添加了一个字母而得到,请找出添加的那个字母。


    思路
    与在一堆重复两次的数中找出一个单独只存在一个的数的问题一样,用异或操作消除所有重复的元素,剩余的元素即为所求

    class Solution {
    public:
        char findTheDifference(string s, string t) {
            int tmp=0;
            for(char c:s){
                tmp ^=c;
            }
            for(char c:t){
                tmp ^=c;
            }
            return char(tmp);
        }
    };
    
    public class Solution {
        public char findTheDifference(String s, String t) {
            char[] cs=s.toCharArray();
            char[] ct=t.toCharArray();
            char tmp=0;
            for(char c:cs)
                tmp^=c;
            for(char c:ct)
                tmp^=c;
            return tmp;
        }
    }
    

    相关文章

      网友评论

          本文标题:389. Find the Difference 找不同

          本文链接:https://www.haomeiwen.com/subject/aiphlxtx.html