题目:给定两个字符串 s 和 t ,它们只蕴含小写字母。
字符串 t 由字符串 s 随机重排,而后在随机地位增加一个字母。
请找出在 t 中被增加的字母。
链接: 力扣Leetcode - 389. 找不同.
示例1:
输出:s = "abcd", t = "abcde"
输入:"e"
解释:'e' 是那个被增加的字母。
示例 2:
输出:s = "", t = "y"
输入:"y"
思路:将字符串 s 和字符串 t 中每个字符的 ASCII 码的值求和,失去 sumS 和 sumT 。两者的差值 sumT - sumS 即代表了被增加的字符。
次要Go代码如下:
package mainimport "fmt"func findTheDifference(s, t string) byte { sumS, sumT := 0, 0 for _, ch := range s { sumS += int(ch) } for _, ch := range t { sumT += int(ch) } return byte(sumT - sumS)}func main() { fmt.Println(findTheDifference("abcd", "abcde"))}
提交截图: