Leetcode 1880. Check if Word Equals Summation of Two Words
You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters.
You need to determine if the summation of the numeric values of firstWord and secondWord equals the numeric value of targetWord.
The numeric value of a word is defined by concatenating the differences between each letter and ‘a’. For instance, the numeric value of “acb” is defined as “021”, representing the concatenation of 0 for ‘a’, 2 for ‘c’, and 1 for ‘b’.
firstWord, secondWord, and targetWord?
true if the numeric value of firstWord + secondWord equals the numeric value of targetWord, otherwise false.firstWord, secondWord, and targetWord to their respective numeric values.#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
bool isSumEqual(string firstWord, string secondWord, string targetWord) {
int num1 = convertToNumericValue(firstWord);
int num2 = convertToNumericValue(secondWord);
int targetNum = convertToNumericValue(targetWord);
return (num1 + num2) == targetNum;
}
private:
int convertToNumericValue(const string& word) {
int numericValue = 0;
for (char c : word) {
numericValue = numericValue * 10 + (c - 'a');
}
return numericValue;
}
};
int main() {
Solution solution;
cout << boolalpha << solution.isSumEqual("acb", "cba", "cdb") << endl; // Output: true
cout << boolalpha << solution.isSumEqual("aaa", "a", "aab") << endl; // Output: false
cout << boolalpha << solution.isSumEqual("aaa", "a", "aaaa") << endl; // Output: true
return 0;
}
isSumEqual is O(n), as it requires converting each of the three strings, ultimately leading to a constant time complexity given the maximum input length.This solution efficiently addresses the problem using string manipulation and integer arithmetic constrained by given inputs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?