Skip to content

Commit 5dfcbe7

Browse files
committed
Palindrome Permutation (#158)
* Palindrome Permutation * Replace list comprehension with constructor
1 parent c11933c commit 5dfcbe7

3 files changed

Lines changed: 61 additions & 0 deletions

File tree

‎strings/README.md‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
* [Longest Common Prefix](#longest-common-prefix)
99
* [Longest Substring Without Duplicates](#longest-substring-without-duplicates)
1010
* [Multiply Strings](#multiply-strings)
11+
* [Palindrome Permutation](#palindrome-permutation)
1112
* [Pangram](#pangram)
1213
* [Reverse String](#reverse-string)
1314
* [Reverse Words In A Sentence](#reverse-words-in-a-sentence)
@@ -314,6 +315,39 @@ def multiply_strings(num1: str, num2: str) -> str:
314315
return str(string_to_int(num1) * string_to_int(num2))
315316
```
316317

318+
## Palindrome Permutation
319+
320+
Given a string, determine if a permutation of the string could form a palindrome.
321+
322+
Example 1:
323+
Input: `"code"`
324+
Output: `false`
325+
326+
Example 2:
327+
Input: `"aab"`
328+
Output: `true`
329+
330+
Example 3:
331+
Input: `"carerac"`
332+
Output: `true`
333+
334+
```python
335+
def palindrome_permutation(palindrome: str) -> bool:
336+
length = len(palindrome)
337+
counter = Counter([char for char in palindrome])
338+
339+
if length % 2 == 0:
340+
for key in counter:
341+
if counter[key] % 2 != 0:
342+
return False
343+
else:
344+
ones_count = Counter(counter.values()).get(1)
345+
if ones_count > 1:
346+
return False
347+
348+
return True
349+
```
350+
317351
## Pangram
318352

319353
Determine if a string has all characters a-z. Should handle uppercase, lowercase, whitespace, and special characters.

‎strings/palindrome_permutation.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from collections import Counter
2+
3+
4+
def palindrome_permutation(palindrome: str) -> bool:
5+
length = len(palindrome)
6+
counter = Counter(list(palindrome))
7+
8+
if length % 2 == 0:
9+
for key in counter:
10+
if counter[key] % 2 != 0:
11+
return False
12+
else:
13+
ones_count = Counter(counter.values()).get(1)
14+
if ones_count > 1:
15+
return False
16+
17+
return True
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
from strings.palindrome_permutation import palindrome_permutation
2+
3+
4+
def test_palindrome_permutation():
5+
assert palindrome_permutation('aabb')
6+
assert palindrome_permutation('aab')
7+
assert palindrome_permutation('aba')
8+
assert palindrome_permutation('')
9+
assert not palindrome_permutation('test')
10+
assert not palindrome_permutation('aabc')

0 commit comments

Comments
 (0)