Skip to content

Instantly share code, notes, and snippets.

@andrewmeissner
Created December 1, 2020 20:50
Show Gist options
  • Save andrewmeissner/e57cbaf13a66ebf176770e4bd56a336b to your computer and use it in GitHub Desktop.
Save andrewmeissner/e57cbaf13a66ebf176770e4bd56a336b to your computer and use it in GitHub Desktop.
Case permutations of a given word
package main
import (
"fmt"
)
func main() {
key := "hello"
words := letterCasePermutation(key)
fmt.Println(words)
}
func letterCasePermutation(S string) []string {
ans := []string{}
// Use DFS to generate all letter permutations of string: S.
// Recursively call to transform one character at a time.
dfs([]byte(S), 0, &ans)
return ans
}
// s is the transformed string.
// i is the index of character to be transformed.
func dfs(s []byte, i int, ans *[]string) {
if i == len(s) {
// All characters have been transformed, add it to answers.
*ans = append(*ans, string(s))
return
}
// Original string.
dfs(s, i+1, ans)
// Transform string, if character at index: i is an alphabet.
if isAlphabet(s[i]) {
s[i] ^= (1 << 5)
dfs(s, i+1, ans)
}
}
func isAlphabet(c byte) bool {
if (c >= 65 && c <= 90) || (c >= 97 && c <= 122) {
return true
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment