Skip to content

Commit c3799cf

Browse files
committed
Update Palindrome Permutation Solution to a more Swift way
1 parent ae683d3 commit c3799cf

File tree

1 file changed

+18
-24
lines changed

1 file changed

+18
-24
lines changed

String/PalindromePermutation.swift

Lines changed: 18 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,29 +5,23 @@
55
*/
66

77
class PalindromePermutation {
8-
func canPermutePalindrome(s: String) -> Bool {
9-
let sChars = [Character](s.characters)
10-
var oddNum = 0
11-
var charFrequency = [Character: Int]()
12-
13-
for char in sChars {
14-
if charFrequency[char] != nil {
15-
charFrequency[char]! += 1
16-
} else {
17-
charFrequency[char] = 1
18-
}
19-
}
20-
21-
for char in charFrequency.keys {
22-
let fre = charFrequency[char]!
23-
if fre % 2 == 1 {
24-
oddNum += 1
25-
}
26-
if oddNum >= 2 {
27-
return false
28-
}
29-
}
30-
31-
return true
8+
func canPermutePalindrome(_ s: String) -> Bool {
9+
var oddNum = 0
10+
11+
for (_, value) in s.frequencies where value % 2 == 1 {
12+
oddNum += 1
13+
14+
if oddNum >= 2 {
15+
return false
16+
}
3217
}
18+
19+
return true
20+
}
21+
}
22+
23+
extension Sequence where Element: Hashable {
24+
var frequencies: [Element: Int] {
25+
return Dictionary(self.map{ ($0, 1)}, uniquingKeysWith: +)
26+
}
3327
}

0 commit comments

Comments
 (0)