1 回答

TA貢獻1777條經(jīng)驗 獲得超3個贊
您實際上只需要相同位置的字符計數(shù),以及每個字符串中每個字符的總計數(shù)。然后對每個字符的最小計數(shù)求和,并在同一位置減去該計數(shù)。
https://play.golang.org/p/pknsVfZ1ZbM
package main
import (
"fmt"
"math"
)
func main() {
a := []rune("abacdead")
b := []rune("adcbadedga")
same := 0
chars := make(map[rune][]int)
for i := 0; i < len(a); i++ {
if i < len(b) && a[i] == b[i] {
same++
}
if _, ok := chars[a[i]]; !ok {
chars[a[i]] = []int{0, 0}
}
chars[a[i]][0]++
}
for i := 0; i < len(b); i++ {
if _, ok := chars[b[i]]; !ok {
chars[b[i]] = []int{0, 0}
}
chars[b[i]][1]++
}
different := -same
for char, vals := range chars {
fmt.Println(string(char), vals[0], vals[1])
different += int(math.Min(float64(vals[0]), float64(vals[1])))
}
fmt.Println("Same: ", same, "Different: ", different)
}
需要注意的是,總數(shù)與您所說的不一致:
"abacdead"
"adcbadedga"
相同的位置,我們有第一個和最后一個,如果我們刪除它們:ad
"bacdea"
"dcbadega"
,然后排序
"aabcde"
"aabcddeg"
然后我們刪除不匹配的字母
"aabcde"
"aabcde"
我們應(yīng)該在不同的位置有六個相同的字符。
- 1 回答
- 0 關(guān)注
- 144 瀏覽
添加回答
舉報