Created
July 24, 2018 19:09
-
-
Save cashlo/0f9ace1099893c2ee17b6d233e34eb04 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution(object): | |
def addString(self, prefix, s, k, chars): | |
print 'AddString({},{},{},{})'.format(prefix, s, k, chars) | |
if len(prefix) == len(s): | |
return prefix | |
for (c,n) in chars.items(): | |
# print prefix[-k+1:] | |
if c not in prefix[-k+1:] and n > 0: | |
chars[c] -= 1 | |
answer = self.addString(prefix + c, s, k, chars) | |
chars[c] += 1 | |
if answer: | |
return answer | |
return '' | |
def rearrangeString(self, s, k): | |
""" | |
:type s: str | |
:type k: int | |
:rtype: str | |
""" | |
char_set = collections.Counter(c for c in s) | |
if len(s) == 1 or k <= 1: | |
return s | |
if len(char_set) < k: | |
return '' | |
result = '' | |
for (c,n) in char_set.items(): | |
char_set[c] -= 1 | |
answer = self.addString(c, s, k, char_set) | |
char_set[c] += 1 | |
if answer: | |
return answer | |
return '' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment