[LeetCode] Check if Word Equals Summation of Two Words

1880. Check if Word Equals Summation of Two Words

The letter value of a letter is its position in the alphabet starting from 0 (i.e. ‘a’ -> 0, ‘b’ -> 1, ‘c’ -> 2, etc.).

The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer.

  • For example, if s = “acb”, we concatenate each letter’s letter value, resulting in “021”. After converting it, we get 21.

You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters ‘a’ through ‘j’ inclusive.

Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
long mutate(string& s) {
stringstream ss;
for(auto& c : s) {
switch (c) {
case 'a': ss<<'0'; break;
case 'b': ss<<'1'; break;
case 'c': ss<<'2'; break;
case 'd': ss<<'3'; break;
case 'e': ss<<'4'; break;
case 'f': ss<<'5'; break;
case 'g': ss<<'6'; break;
case 'h': ss<<'7'; break;
case 'i': ss<<'8'; break;
case 'j': ss<<'9'; break;
}
}
return stol(ss.str());
}
public:
bool isSumEqual(string firstWord, string secondWord, string targetWord) {
return (mutate(firstWord) + mutate(secondWord)) == mutate(targetWord);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/30/PS/LeetCode/check-if-word-equals-summation-of-two-words/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.