Skip to content

Commit

Permalink
Q1.4: Palindrome permutation, simplified implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
krlv committed Mar 3, 2019
1 parent ea908fc commit 88cee3c
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
23 changes: 23 additions & 0 deletions ch01/palindrome_permutation.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,26 @@ func IsPalindromePermutation(s string) bool {

return true
}

// IsPalindromePermutationSimplified returns true if a srting is a palindrome permutation
// It uses a single for loop to check the permutations
func IsPalindromePermutationSimplified(s string) bool {
set := make(map[rune]int)
odd := 0

for _, c := range s {
if c == ' ' {
continue
}

set[c]++

if set[c]%2 != 0 {
odd++
} else {
odd--
}
}

return !(odd > 1)
}
17 changes: 17 additions & 0 deletions ch01/palindrome_permutation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,21 @@ func TestIsPalindromePermutation(t *testing.T) {
if !IsPalindromePermutation(s) {
t.Errorf("\"%s\" expected to be marked as a palindrome permutation", s)
}

s = "tacos cat"
if IsPalindromePermutation(s) {
t.Errorf("\"%s\" expected not to be marked as a palindrome permutation", s)
}
}

func TestIsPalindromePermutationSimplified(t *testing.T) {
s := "taco cat"
if !IsPalindromePermutationSimplified(s) {
t.Errorf("\"%s\" expected to be marked as a palindrome permutation", s)
}

s = "tacos cat"
if IsPalindromePermutationSimplified(s) {
t.Errorf("\"%s\" expected not to be marked as a palindrome permutation", s)
}
}

0 comments on commit 88cee3c

Please sign in to comment.