From f76a069a6eb1b4ebc72e54595dd34ea03ef7b31f Mon Sep 17 00:00:00 2001 From: dobin Date: Sat, 26 Dec 2020 18:03:56 +0900 Subject: [PATCH] Add reorganize-string.py & Updated README.md --- Python/reorganize-string.py | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 Python/reorganize-string.py diff --git a/Python/reorganize-string.py b/Python/reorganize-string.py new file mode 100644 index 00000000..78450197 --- /dev/null +++ b/Python/reorganize-string.py @@ -0,0 +1,26 @@ +''' +speed: 89.11% +memory: 21:02% +N = len(S), A = 1~26(size of diff alpabet) +ex) aab, N=3, A=2 +time complexity: O(A * (N + logA)) +space complexity: O(N) +''' +class Solution: + def reorganizeString(self, S: str) -> str: + n = len(S) + a= [] + + for c,x in sorted((S.count(x), x) for x in set(S)): + if c > (n+1)/2: # not possible + return '' + a.extend(c*x) + + # empty list + ans = [None] * n + + # placing letters to make possible result + ans[::2], ans[1::2] = a[n//2:], a[:n//2] + return "".join(ans) + + \ No newline at end of file diff --git a/README.md b/README.md index e455cc8c..33b728ed 100644 --- a/README.md +++ b/README.md @@ -160,6 +160,7 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu | 1374 | [Generate a String With Characters That Have Odd Counts](https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/) | [Java](./Java/generate-a-string-with-characters-that-have-odd-counts.java) | _O(n)_ | _O(1)_ | Easy | | | | 859 | [Buddy Strings](https://leetcode.com/problems/buddy-strings/) | [Java](./Java/buddy-strings.java) | _O(n)_ | _O(1)_ | Easy | | | | 9 | [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [Java](./Java/palindrome-number.java) | _O(n)_ | _O(1)_ | Easy | | | +| 767 | [Reorganize String](https://leetcode.com/problems/reorganize-string/) | [Python](./Python/reorganize-string.py) | _O(n)_ | _O(n)_ | Medium | | |
⬆️ Back to Top