LyWang

anagram2

Nov 18th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.25 KB | None | 0 0
  1. from typing import List, Any
  2.  
  3. class Solution:
  4.     def anagrams(self,strs):
  5.         strs_comp = strs.copy()
  6.         if len(strs_comp) == 0:
  7.             return []  # trivial case
  8.         else:
  9.             answer = [] # we keep an answer array to store all sorted anagrams
  10.             k = 0
  11.             strs_comp = sorted(strs_comp).copy()
  12.             original: List[Any] = strs_comp.copy()  # save for later output
  13.             for i in range(len(original)):
  14.                 if strs_comp[i] != '':
  15.                     strs_comp[i] = ''.join(sorted(strs_comp[i]))
  16.                     #we sort everything, hold the length 0 exception
  17.             while k < len(strs_comp):
  18.                 #start to iterate
  19.                 if strs_comp[k] not in answer:
  20.                     if strs_comp[k] in strs_comp[k+1:]:
  21.                          answer.append(strs_comp[k])
  22.                          k+=1
  23.                          #match but not in answer, update answer and next
  24.                     else:
  25.                         #not match not in answer
  26.                         strs_comp.pop(k)
  27.                         original.pop(k)
  28.                 else:
  29.                     k+=1
  30.                     #got something in answer, next
  31.             return original
Add Comment
Please, Sign In to add comment