2 minutes
Leetcode 266
The idea of this solution is pretty simple. We add all the letters to a map, and then if there is a extra letter that does not have a partner for the other end of the palindrome add it to the numberOfOnes
counter, if the counter is greater than 1
we know that it is not a palindrome. We can explain this with some examples:
There are three main examples that are going to be shown:
input: "aabbccd", expected output: true
, we can make a mapm := ['a' : 2, 'b' : 2, 'c' : 2, 'd' : 1]
if we iterate throughm
we can returntrue
becausenumberOfOnes = 1
.numberOfOnes = 1
because'd' : 1
. If you don’t understand why we returntrue
see that we can swap the letters around to get"abcdcba"
.input: "aabb", expected output: true
, we can also make a mapm := ['a' : 2, 'b' : 2]
. When we iterate throughm
we getnumberOfOnes = 0
so we retun true. When we swap around"aabb"
we get"abba"
which is a palindrome.input: "aabbcd", expected output: false
. We can make a mapm := ['a' : 2, 'b' : 2, 'c' : 1, 'd' : 1]
. When we iterate throughm
we can see thatnumberOfOnes = 2
and sincenumberOfOnes > 1
we returnfalse
. We returnfalse
because however we swap around"aabbcd"
we can never get a palindrome because there is an extrac
andd
.
func canPermutePalindrome(s string) bool {
m := make(map[rune]int)
numberOfOnes := 0
for _, i := range s {
m[i]++
}
for _, i := range m {
numberOfOnes += i % 2
}
return numberOfOnes <= 1
}
Read other posts