leetcode 389. Find the Difference

浅浅的花香味﹌ 2022-06-01 09:12 268阅读 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.

本题很简单,就是寻找额外添加的元素,其实使用Map计数统计即可,

下面是C++的做法,

直接统计然后计数即可

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <unordered_map>
  5. #include <set>
  6. #include <unordered_set>
  7. #include <queue>
  8. #include <stack>
  9. #include <string>
  10. #include <climits>
  11. #include <algorithm>
  12. #include <sstream>
  13. #include <functional>
  14. #include <bitset>
  15. #include <numeric>
  16. #include <cmath>
  17. #include <regex>
  18. using namespace std;
  19. class Solution
  20. {
  21. public:
  22. char findTheDifference(string s, string t)
  23. {
  24. vector<int> count1(26, 0);
  25. vector<int> count2(26, 0);
  26. for (char c : s)
  27. count1[c - 'a']++;
  28. for (char c : t)
  29. count2[c - 'a']++;
  30. for (int i = 0; i < 26; i++)
  31. {
  32. if (count1[i] != count2[i])
  33. return (char)(i + 'a');
  34. }
  35. return 0;
  36. }
  37. };

发表评论

表情:
评论列表 (有 0 条评论,268人围观)

还没有评论,来说两句吧...

相关阅读