LeetCode 0767. Reorganize String Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0767. Reorganize String

Description

Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.

Return any possible rearrangement of s or return "" if not possible.

 

Example 1:

Input: s = "aab"
Output: "aba"

Example 2:

Input: s = "aaab"
Output: ""

 

Constraints:

  • 1 <= s.length <= 500
  • s consists of lowercase English letters.

Solutions

Solution 1

PythonJavaC++GoRust
class Solution: def reorganizeString(self, s: str) -> str: n = len(s) cnt = Counter(s) mx = max(cnt.values()) if mx > (n + 1) // 2: return '' i = 0 ans = [None] * n for k, v in cnt.most_common(): while v: ans[i] = k v -= 1 i += 2 if i >= n: i = 1 return ''.join(ans)(code-box)

Solution 2

PythonJavaC++Go
class Solution: def reorganizeString(self, s: str) -> str: return self.rearrangeString(s, 2) def rearrangeString(self, s: str, k: int) -> str: h = [(-v, c) for c, v in Counter(s).items()] heapify(h) q = deque() ans = [] while h: v, c = heappop(h) v *= -1 ans.append(c) q.append((v - 1, c)) if len(q) >= k: w, c = q.popleft() if w: heappush(h, (-w, c)) return "" if len(ans) != len(s) else "".join(ans)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !