ETH官方钱包

前往
大廳
主題

LeetCode - 1880. Check if Word Equals Summation of Two Words 解題心得

Not In My Back Yard | 2021-07-25 00:00:01 | 巴幣 0 | 人氣 232

題目連結(jié):


題目意譯:
一個(gè)字母的字母值為其位於字母表中從 0 開始數(shù)的位置(即 'a' → 0 、 'b' → 1 、 'c' → 2,以此類推)。

一個(gè)小寫英文字母之字串 s 的數(shù)值為 s 中每個(gè)字母的字母值之串接,其將轉(zhuǎn)換為一整數(shù)。

例如,如果 s = "acb",我們串接每個(gè)字母的字母值,得到 "021"。接著轉(zhuǎn)為整數(shù),得到 21 。

你被給定三個(gè)字串 firstWord 、 secondWord 和 targetWord ,每個(gè)皆由小寫英文字母 'a'(含)到 'j'(含)組成。

回傳真(True)如果 firstWord 與 secondWord 的數(shù)值之和等於 targetWord 之?dāng)?shù)值;反之為假(False)。

限制:
1 ≦ firstWord.length 、 secondWord.length 、 targetWord.length ≦ 8
firstWord 、 secondWord 和 targetWord 由小寫英文字母 'a'(含)到 'j'(含)組成。



範(fàn)例測(cè)資:
範(fàn)例 1:
輸入: firstWord = "acb", secondWord = "cba", targetWord = "cdb"
輸出: true
解釋:
firstWord 的數(shù)值為 "acb" → "021" → 21。
secondWord 的數(shù)值為 "cba" → "210" → 210。
targetWord 的數(shù)值為 "cdb" → "231" → 231。
我們回傳真,因?yàn)?21 + 210 == 231。

範(fàn)例 2:
輸入: firstWord = "aaa", secondWord = "a", targetWord = "aab"
輸出: false
解釋:
firstWord 的數(shù)值為 "aaa" → "000" → 0。
secondWord 的數(shù)值為 "a" → "0" → 0。
targetWord 的數(shù)值為 "aab" → "001" → 1。
我們回傳假,因?yàn)?0 + 0 != 1。

範(fàn)例 3:
輸入: firstWord = "aaa", secondWord = "a", targetWord = "aaaa"
輸出: true
解釋:
firstWord 的數(shù)值為 "aaa" → "000" → 0。
secondWord 的數(shù)值為 "a" → "0" → 0。
targetWord 的數(shù)值為 "aaaa" → "0000" → 0。
我們回傳真,因?yàn)?0 + 0 == 0。


解題思維:
可以直接將 firstWord 、 secondWord 轉(zhuǎn)成對(duì)應(yīng)的整數(shù),然後看是否相加後等於 targetWord 轉(zhuǎn)成整數(shù)後的結(jié)果。當(dāng)然,也可以直接作字串加法(如這題),然後看相加結(jié)果是否等於 targetWord 。




此次分享到此為止,如有任何更加簡(jiǎn)潔的想法或是有說明不清楚之地方,也煩請(qǐng)各位大大撥冗討論。

創(chuàng)作回應(yīng)

追蹤 創(chuàng)作集

作者相關(guān)創(chuàng)作

更多創(chuàng)作