Iam_Sandeep

767. Reorganize String

Jul 23rd, 2022 (edited)
1,078
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. '''
  2. Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.
  3. Return any possible rearrangement of s or return "" if not possible.
  4. Example 1:
  5. Input: s = "aab"
  6. Output: "aba"
  7. '''
  8. #M1
  9. class Solution:
  10.     def reorganizeString(self, s: str) -> str:
  11.         d=Counter(s)
  12.         n=len(s)
  13.         mkey,mval = d.most_common(1)[0]
  14.        
  15.         if mval > (n+1)>>1:
  16.             return ""
  17.         ans = [None]*n
  18.        
  19.         i = 0
  20.         for _ in range(mval):
  21.             ans[i] = mkey
  22.             i = (i+2)%n
  23.        
  24.         for key in d.keys():
  25.             if key == mkey:continue
  26.             for _ in range(d[key]):
  27.                 while ans[i] != None:i += 1
  28.                 ans[i] = key
  29.                 i = (i+2)%n
  30.    
  31.         return ''.join(ans)
  32. #M2
  33. class Solution:
  34.     def reorganizeString(self, s: str) -> str:
  35.         n=len(s)
  36.         freq=[0]*26
  37.         for i in s:
  38.             freq[ord(i)-97]+=1
  39.         maxi = max(freq) #max frequency caluculate
  40.         if maxi>(n+1)//2 : #if this condition happens then surely you cant make reorganized string
  41.             return ""
  42.         ans = [None]*n
  43.         char = chr(freq.index(maxi)+97)
  44.        
  45.         idx=0
  46.         while maxi:
  47.             ans[idx]=char
  48.             idx +=2
  49.             maxi-=1
  50.             if idx>=n:
  51.                 idx=1
  52.        
  53.         freq[ord(char)-97]=0
  54.    
  55.         for i in range(26):
  56.             while freq[i]>0:
  57.                 freq[i]-=1
  58.                 ans[idx]= chr(i+97)
  59.                 idx+=2
  60.                 if idx>=n:
  61.                     idx=1
  62.                    
  63.         return ''.join(ans)
  64.                
  65.            
  66.        
  67.        
Advertisement
Add Comment
Please, Sign In to add comment