Skip to content

Commit d4d232c

Browse files
committed
Sync LeetCode submission Runtime - 51 ms (25.11%), Memory - 18.2 MB (8.81%)
1 parent 52f12e6 commit d4d232c

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<p>Given a string <code>s</code> and an integer <code>k</code>, return <code>true</code> <em>if you can use all the characters in </em><code>s</code><em> to construct </em><code>k</code><em> palindrome strings or </em><code>false</code><em> otherwise</em>.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
6+
<pre>
7+
<strong>Input:</strong> s = &quot;annabelle&quot;, k = 2
8+
<strong>Output:</strong> true
9+
<strong>Explanation:</strong> You can construct two palindromes using all characters in s.
10+
Some possible constructions &quot;anna&quot; + &quot;elble&quot;, &quot;anbna&quot; + &quot;elle&quot;, &quot;anellena&quot; + &quot;b&quot;
11+
</pre>
12+
13+
<p><strong class="example">Example 2:</strong></p>
14+
15+
<pre>
16+
<strong>Input:</strong> s = &quot;leetcode&quot;, k = 3
17+
<strong>Output:</strong> false
18+
<strong>Explanation:</strong> It is impossible to construct 3 palindromes using all the characters of s.
19+
</pre>
20+
21+
<p><strong class="example">Example 3:</strong></p>
22+
23+
<pre>
24+
<strong>Input:</strong> s = &quot;true&quot;, k = 4
25+
<strong>Output:</strong> true
26+
<strong>Explanation:</strong> The only possible solution is to put each character in a separate string.
27+
</pre>
28+
29+
<p>&nbsp;</p>
30+
<p><strong>Constraints:</strong></p>
31+
32+
<ul>
33+
<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>
34+
<li><code>s</code> consists of lowercase English letters.</li>
35+
<li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li>
36+
</ul>
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Approach 1: Count Odd Frequencies
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def canConstruct(self, s: str, k: int) -> bool:
8+
if len(s) < k:
9+
return False
10+
if len(s) == k:
11+
return True
12+
13+
freq = [0] * 26
14+
odd_count = 0
15+
16+
for char in s:
17+
freq[ord(char) - ord('a')] += 1
18+
19+
for count in freq:
20+
if count % 2 == 1:
21+
odd_count += 1
22+
23+
return odd_count <= k
24+

0 commit comments

Comments
 (0)