检查某单词是否等于两单词之和

题目

字母的 字母值 取决于字母在字母表中的位置,从 0 开始 计数。即,'a' -> 0'b' -> 1'c' -> 2,以此类推。

对某个由小写字母组成的字符串 s 而言,其 数值 就等于将 s中每个字母的 字母值 按顺序 连接转换 成对应整数。

  • 例如,s = "acb",依次连接每个字母的字母值可以得到"021",转换为整数得到21

给你三个字符串 firstWordsecondWordtargetWord ,每个字符串都由从 'a''j'(含'a''j' )的小写英文字母组成。
如果 firstWordsecondWord数值之和 等于 targetWord 的数值,返回 true ;否则,返回 false

示例

示例1
输入:firstWord = "acb", secondWord = "cba", targetWord = "cdb"
输出:true
解释:
firstWord 的数值为 "acb" -> "021" -> 21
secondWord 的数值为 "cba" -> "210" -> 210
targetWord 的数值为 "cdb" -> "231" -> 231
由于 21 + 210 == 231 ,返回 true
示例2
输入:firstWord = "aaa", secondWord = "a", targetWord = "aab"
输出:false
解释:
firstWord 的数值为 "aaa" -> "000" -> 0
secondWord 的数值为 "a" -> "0" -> 0
targetWord 的数值为 "aab" -> "001" -> 1
由于 0 + 0 != 1 ,返回 false
示例3
输入:firstWord = "aaa", secondWord = "a", targetWord = "aaaa"
输出:true
解释:
firstWord 的数值为 "aaa" -> "000" -> 0
secondWord 的数值为 "a" -> "0" -> 0
targetWord 的数值为 "aaaa" -> "0000" -> 0
由于 0 + 0 == 0 ,返回 true

提示

  • 1 <= firstWord.length, secondWord.length, targetWord.length <= 8
  • firstWord、secondWord 和 targetWord 仅由从 ‘a’ 到 ‘j’ (含 ‘a’ 和 ‘j’ )的小写英文字母组成。

题解

方法一:按要求处理

思路与算法

我们用函数 d e c o d e ( s ) decode(s) decode(s)将单词转化为对应的整数。我们将 r e s res res 的初始值设为 0 0 0,在从前至后处理每个字符 s [ i ] s[i] s[i] 时,我们需要将 r e s res res 10 10 10 并加上 s [ i ] s[i] s[i] 对应的数值。最终,我们返回 r e s res res 作为转化后的整数。

最终,我们比较 d e c o d e ( f i r s t W o r d ) decode(firstWord) decode(firstWord) d e c o d e ( s e c o n d W o r d ) decode(secondWord) decode(secondWord) 的和是否等于 d e c o d e ( t a r g e t W o r d ) decode(targetWord) decode(targetWord) 即可。

代码
class Solution {
    public boolean isSumEqual(String firstWord, String secondWord, String targetWord) {
        return decode(firstWord) + decode(secondWord) == decode(targetWord);
    }

    private int decode(String s) {
        int res = 0;
        for (int i = 0; i < s.length(); i++) {
            res *= 10;
            res += s.charAt(i) - 'a';
        }
        return res;
    }
}
复杂度分析
  • 时间复杂度: O ( n 1 + n 2 + n 3 ) O(n_1+n_2+n_3) O(n1+n2+n3),其中 n 1 , n 2 , n 3 n_1, n_2, n_3 n1,n2,n3分别为三个字符串的长度。我们需要分别遍历三个字符串并转为对应的整数。
  • 空间复杂度: O ( 1 ) O(1) O(1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值