Article directory
1. The topic
2. Solution A
2.1 Ideas
Use cnt to identify, corresponding to the number of different characters at the subscript
- Returns true if 0
- Returns false if 1
- Returns true if it is 2 and the two characters are the same
- Returns false if it is 2 and the two characters are different
- Returns false if > 2.
2.2 Coding
package main
func main() {
if x := areAlmostEqual("bf", "dd"); x != false {
panic(x)
}
if x := areAlmostEqual("bf", "fb"); x != true {
panic(x)
}
select {
}
}
func areAlmostEqual(s1, s2 string) bool {
var c1, c2 byte
cnt := 0
for i := range s1 {
if s1[i] != s2[i] {
cnt++
if cnt > 2 || (cnt == 2 && s1[i] != c1 && s2[i] != c2) {
return false
}
c1, c2 = s1[i], s2[i]
}
}
return cnt != 1
}
3. Solution B
3.1 Ideas
The title says that two strings are of equal length, but to find a string that only needs to be exchanged once to be successful
So there are only two cases:
- Case 1: Both strings are exactly the same
- Case 2: Swap the two characters of the s1 string to get s2
You can traverse the string once and compare the two characters s1[i] and s2[i] in the same position
- If after traversing, there are 0 different characters, then case 1 is met
- If traversing the sum, there are 2 different characters, and the first different characters are x1, x2; and the second different characters are x2, x1, then case 2 is satisfied
Therefore, the following data structure is used to implement:
- Represent the number of different characters by diffCount
- Return false directly when diffCount > 2
- When diffCount == 0, it means that the first two different characters have been traversed, and the two characters are identified as x1, x2
- When diffCount == 1, it means that two different characters have been traversed for the second time, and the two characters are identified as y1, y2
- After the traversal is over, if diffCount == 0, return true, which is consistent with case 1
- After the traversal, if diffCount == 2, and
x1 == y2 && x2 == y1
, return true, which is consistent with case 2
3.1 Coding
package main
func main() {
if x := areAlmostEqual("bf", "dd"); x != false {
panic(x)
}
if x := areAlmostEqual("bf", "fb"); x != true {
panic(x)
}
select {
}
}
func areAlmostEqual(s1 string, s2 string) bool {
diffCount := 0
x1 := uint8(0) // prevDiffValueInS1
x2 := uint8(0) // prevDiffValueInS2
y1 := uint8(0) // afterDiffValueInS1
y2 := uint8(0) // afterDiffValueInS2
for i := range s1 {
if s1[i] != s2[i] {
if diffCount == 0 {
x1 = s1[i]
x2 = s2[i]
} else if diffCount == 1 {
y1 = s1[i]
y2 = s2[i]
if x1 != y2 || x2 != y1 {
return false
}
}
diffCount++
if diffCount > 2 {
return false
}
}
}
return diffCount == 0 || (diffCount == 2 && x1 == y2 && x2 == y1)
}