forked from realpacific/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIsPermutationOfStringAPalindrome.kt
38 lines (33 loc) · 1.14 KB
/
IsPermutationOfStringAPalindrome.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package arraysandstrings
import _utils.UseCommentAsDocumentation
import arraysandstrings.IsPermutationOfStringAPalindrome.isPalindrome
import kotlin.test.assertFalse
import kotlin.test.assertTrue
private object IsPermutationOfStringAPalindrome {
/**
* A string's permutation is a palindrome
* if
* for a odd length string, there must be only one odd # of character (the middle one)
* for a even length string, all chars must have even # of occurrence
*/
@UseCommentAsDocumentation
fun isPalindrome(str: String): Boolean {
val input = str.toLowerCase().replace(" ", "")
val charCount = mutableMapOf<Char, Int>()
for (s in input) {
charCount[s] = (charCount[s] ?: 0) + 1
}
return if (input.length % 2 == 0) {
charCount.values.all { it % 2 == 0 }
} else {
val oddOccurrence = charCount.values.filter { it % 2 == 1 }
oddOccurrence.size == 1
}
}
}
fun main() {
assertTrue(isPalindrome("Tact Coa"))
assertTrue(isPalindrome("level"))
assertTrue(isPalindrome("noon"))
assertFalse(isPalindrome("noon2a"))
}