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.
思路一: 用一个 26 长度的数组映射 a-z 的值,然后计算字符串对应的值即可
public boolean isSumEqual(String firstWord, String secondWord, String targetWord) {
int[] arr = new int[26];
for (char i = 0; i < 26; i++) {
arr[i] = i;
}
return val(arr, firstWord) + val(arr, secondWord) == val(arr, targetWord);
}
public int val(int[] arr, String str) {
int sum = 0;
int n = 1;
for (int i = str.length() - 1; i >= 0; i--) {
sum += arr[str.charAt(i) - 'a'] * n;
n *= 10;
}
return sum;
}
标签:arr,easy,val,int,String,letter,firstWord,leetcode,1880
From: https://www.cnblogs.com/iyiluo/p/16853174.html