letecode [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.

Example:

Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.

题目大意

  给定字符s,将s打乱顺序后随机插入一个字符,找到这个字符。

理  解:

  方法一:数组统计法。

      数组统计s中所有字符出现的次数。遍历t时每遇到一个字符-1,当计数为-1时,找到该字符。

  方法二:直接法。  

      用t所有字符和减s所有字符和,即为该字符。

代 码 C++:

方法一:

class Solution {
public:
    char findTheDifference(string s, string t) {
        vector<int> count(26);
        for(char ch:s){
            count[ch-'a']++;
        }
        for(char ch:t){
            count[ch-'a']--;
            if(count[ch-'a']==-1)
                return ch;
        }
        return ' ';
    }
};

方法二:

class Solution {
public:
    char findTheDifference(string s, string t) {
        int sum = 0;
        for(char ch:t){
            sum += ch;
        }
        for(char ch:s){
            sum -= ch;
        }
        return sum;
    }
};

运行结果:

方法一:

  执行用时 :16 ms, 在所有 C++ 提交中击败了31.63%的用户
  内存消耗 :8.9 MB, 在所有 C++ 提交中击败了90.43%的用户

方法二:

  执行用时 :8 ms, 在所有 C++ 提交中击败了88.95%的用户
  内存消耗 :9 MB, 在所有 C++ 提交中击败了69.56%的用户
posted @ 2019-06-19 20:30  lpomeloz  阅读(123)  评论(0编辑  收藏  举报