首页 > 其他 > 详细

letecode [389] - Find the Difference

时间:2019-06-19 20:52:14      阅读:91      评论:0      收藏: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,将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%的用户

letecode [389] - Find the Difference

原文:https://www.cnblogs.com/lpomeloz/p/11054469.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!