-
Notifications
You must be signed in to change notification settings - Fork 0
/
0389-Find_the_Difference.cpp
81 lines (73 loc) · 1.7 KB
/
0389-Find_the_Difference.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*******************************************************************************
* 0389-Find_the_Difference.cpp
* Billy.Ljm
* 25 September 2023
*
* =======
* Problem
* =======
* https://leetcode.com/problems/find-the-difference/
*
* You are given two strings s and t.
*
* String t is generated by random shuffling string s and then add one more
* letter at a random position.
*
* Return the letter that was added to t.
*
* ===========
* My Approach
* ===========
* We can sum the letters in each string, as ASCII, and subtract both to find
* their difference.
*
* This has a time complexity of O(n), and a space complexity of O(1), where n
* is the length of the longer string.
******************************************************************************/
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
/**
* << operator for vectors
*/
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
os << "[";
for (const auto elem : v) {
os << elem << ",";
}
if (v.size() > 0) os << "\b";
os << "]";
return os;
}
/**
* Solution
*/
class Solution {
public:
char findTheDifference(string s, string t) {
int out = accumulate(s.begin(), s.end(), 0);
out -= accumulate(t.begin(), t.end(), 0);
out = abs(out);
return '\0' + out;
}
};
/**
* Test cases
*/
int main(void) {
Solution sol;
string s, t;
// test case 1
s = "abcd";
t = "abcde";
std::cout << "findTheDifference(" << s << "," << t << ") = ";
std::cout << sol.findTheDifference(s, t) << std::endl;
// test case 2
s = "";
t = "y";
std::cout << "findTheDifference(" << s << "," << t << ") = ";
std::cout << sol.findTheDifference(s, t) << std::endl;
return 0;
}