[Golang]力扣Leetcode - 389. 找不同(求和)

[Golang]力扣Leetcode - 389. 找不同(求和)

题目:给定两个字符串 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 main

import "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"))
}

提交截图
在这里插入图片描述

posted @ 2022-04-19 10:47  Dancing-Pierre  阅读(15)  评论(0)    收藏  举报  来源