Easy
题目描述
字母的字母值是其在字母表中的位置,从 0 开始(即 ‘a’ -> 0, ‘b’ -> 1, ‘c’ -> 2, 等等)。
某个由小写英文字母组成的字符串 s 的数值是将 s 中每个字母的字母值按顺序连接起来,然后转换成对应的整数。
- 例如,如果 s = “acb”,我们将每个字母的字母值连接起来,得到 “021”。转换为整数后,我们得到 21。
给你三个字符串 firstWord、secondWord 和 targetWord ,每个字符串都由从 ‘a’ 到 ‘j’ (含 ‘a’ 和 ‘j’ )的小写英文字母组成。
如果 firstWord 和 secondWord 的数值之和等于 targetWord 的数值,返回 true ;否则,返回 false 。
示例 1:
输入:firstWord = "acb", secondWord = "cba", targetWord = "cdb"
输出:true
解释:
firstWord 的数值是 "acb" -> "021" -> 21
secondWord 的数值是 "cba" -> "210" -> 210
targetWord 的数值是 "cdb" -> "231" -> 231
返回 true ,因为 21 + 210 == 231
示例 2:
输入:firstWord = "aaa", secondWord = "a", targetWord = "aab"
输出:false
解释:
firstWord 的数值是 "aaa" -> "000" -> 0
secondWord 的数值是 "a" -> "0" -> 0
targetWord 的数值是 "aab" -> "001" -> 1
返回 false ,因为 0 + 0 != 1
示例 3:
输入:firstWord = "aaa", secondWord = "a", targetWord = "aaaa"
输出:true
解释:
firstWord 的数值是 "aaa" -> "000" -> 0
secondWord 的数值是 "a" -> "0" -> 0
targetWord 的数值是 "aaaa" -> "0000" -> 0
返回 true ,因为 0 + 0 == 0
提示:
- 1 <= firstWord.length, secondWord.length, targetWord.length <= 8
- firstWord、secondWord 和 targetWord 仅由从 ‘a’ 到 ‘j’ 的小写英文字母组成
解题思路
这道题需要将字符串转换为对应的数值,然后判断两个数值的和是否等于目标数值。
解题思路:
字符转数字规则:每个字符 ‘a’ 到 ‘j’ 对应数字 0 到 9,即
char - 'a'字符串转数值:遍历字符串中的每个字符,将其对应的数字按位拼接成最终的数值。可以使用数学方法:
result = result * 10 + digit比较判断:分别计算三个字符串的数值,判断前两个数值的和是否等于第三个数值
算法步骤:
- 定义一个辅助函数
getNumValue(),用于将字符串转换为对应的数值 - 在辅助函数中,遍历字符串的每个字符,计算
char - 'a'得到对应数字 - 使用
result = result * 10 + digit的方式构建最终数值 - 分别计算三个字符串的数值,比较
firstValue + secondValue == targetValue
这种方法时间复杂度较低,代码简洁易懂,是最优解法。
代码实现
class Solution {
public:
bool isSumEqual(string firstWord, string secondWord, string targetWord) {
return getNumValue(firstWord) + getNumValue(secondWord) == getNumValue(targetWord);
}
private:
int getNumValue(string word) {
int result = 0;
for (char c : word) {
result = result * 10 + (c - 'a');
}
return result;
}
};
class Solution:
def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:
def getNumValue(word):
result = 0
for c in word:
result = result * 10 + (ord(c) - ord('a'))
return result
return getNumValue(firstWord) + getNumValue(secondWord) == getNumValue(targetWord)
public class Solution {
public bool IsSumEqual(string firstWord, string secondWord, string targetWord) {
return GetNumValue(firstWord) + GetNumValue(secondWord) == GetNumValue(targetWord);
}
private int GetNumValue(string word) {
int result = 0;
foreach (char c in word) {
result = result * 10 + (c - 'a');
}
return result;
}
}
var isSumEqual = function(firstWord, secondWord, targetWord) {
function wordToNum(word) {
let numStr = '';
for (let char of word) {
numStr += (char.charCodeAt(0) - 97);
}
return parseInt(numStr);
}
return wordToNum(firstWord) + wordToNum(secondWord) === wordToNum(targetWord);
};
复杂度分析
| 复杂度类型 | 复杂度 | 说明 |
|---|---|---|
| 时间复杂度 | O(n + m + k) | n, m, k 分别为三个字符串的长度,需要遍历每个字符串一次 |
| 空间复杂度 | O(1) | 只使用了常数级别的额外空间 |