Leetcode Note: Go - Buddy Strings

Buddy Strings - LeetCode
https://leetcode.com/problems/buddy-strings/

  • Go 言語で取り組んだメモ

所感

  • string A, B が渡されるので swap して同じ値 (Buddy Strings) になるか判定して bool で return する

回答

Buddy Strings - LeetCode
https://leetcode.com/problems/buddy-strings/solution/

Go solution: Both runtime and memory beat 100% - LeetCode Discuss
https://leetcode.com/problems/buddy-strings/discuss/441715/Go-solution%3A-Both-runtime-and-memory-beat-100

func buddyStrings(A string, B string) bool {
  if len(A) != len(B) {
		return false
	}
	diff := [2]int{}
	count := 0
	// store duplicate character
	dup := map[byte]int{}
	for i := 0; i < len(A); i++ {
		if (A[i] != B[i]) {
			count++
			if count <= 2 {
				diff[count - 1] = i
			} else {
				return false
			}
		}
		if _, ok := dup[A[i]]; ok {
			dup[A[i]]++
		} else {
			dup[A[i]] = 1
		}
	}
	// A equals to B
	if count == 0 {
		// check whether there has a duplicate character 
		for _, v := range dup {
			if v > 1 {
				return true
			}
		}
	} else if count == 2 {
		if A[diff[0]] == B[diff[1]] && A[diff[1]] == B[diff[0]] {
			return true
		}
	}
	return false
}