luoheng
10/14/2019 - 11:56 AM

buddyStrings

func buddyStrings(A string, B string) bool {
    if len(A) != len(B) {
        return false
    }
    first, second := -1, -1
    for i := 0; i < len(A); i++ {
        if A[i] != B[i] {
            if first == -1 {
                first = i
            } else if second == -1 {
                second = i
            } else {
                return false
            }
        }
    }
    if first == second {
        hash := [26]int{}
        for i := 0; i < len(A); i++ {
            hash[A[i]-'a']++
            if hash[A[i]-'a'] > 1 {
                return true
            }
        }
        return false
    }
    return A[first] == B[second] && A[second] == B[first]
}