Skip to content

Instantly share code, notes, and snippets.

@david415
Created December 17, 2019 01:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save david415/993f9f5852b19fc5db7c9cce0014cb30 to your computer and use it in GitHub Desktop.
Save david415/993f9f5852b19fc5db7c9cce0014cb30 to your computer and use it in GitHub Desktop.
Q1 Strings
package main
import (
"bytes"
"fmt"
)
func isAlmost(x, y []byte) bool {
skipped := false
i := 0
for i < len(x) {
fmt.Printf("comparing x %s and y %s\n", x, y)
if y[i] != x[i] {
fmt.Println("not equal")
if skipped {
return false
}
// delete y[i]
fmt.Printf("deleting one char: %s\n", y[i])
if i == len(y) {
y = y[:i]
} else {
y = append(y[:i], y[i+1:]...)
}
skipped = true
}
i++
}
if skipped {
return true
}
if bytes.Equal(x, y[:len(y)-1]) {
return true
}
return false
}
func equalsWhenOneCharRemoved(x, y string) bool {
if x == y {
return false
}
if len(x) < len(y) {
// case 1: given x and y, x can be obtained by removing
// one element from y
return isAlmost([]byte(x), []byte(y))
} else {
// case 2: given x and y, y can be obtained by removing
// one element from x
return isAlmost([]byte(y), []byte(x))
}
return false
}
func main() {
fmt.Println(equalsWhenOneCharRemoved("123", "1234"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment