# Demo entry 6737204

kims code

Submitted by anonymous on Apr 29, 2018 at 23:12
Language: Python 3. Code size: 1.8 kB.

#Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
#Output:
#[
#  ["ate","eat","tea"],
#  ["nat","tan"],
#  ["bat"]
#]

#Two strings are anagrams if and only if their sorted strings are equal.
#Maintain a map ans : {String -> List} where each key \text{K}K is a sorted string, and each value is the list of strings from the initial input that when sorted, are equal to \text{K}K.

#In Python, we will store the key as a hashable tuple, eg. ('c', 'o', 'd', 'e').

import collections

strs = ["eat", "tea", "tan", "ate", "nat", "bat"]

class Solution(object):
def groupAnagramsSorted(self, strs):
print('sorted strs: ', sorted(strs))
print(' ')
ans = collections.defaultdict(list)

for s in strs:
print('sorted s of strs: ', sorted(s))
ans[tuple(sorted(s))].append(s)
print('tuple update: ', tuple)
print('ans: ', ans)
print(' ')
return ans.values()

ans = Solution().groupAnagramsSorted(strs=strs)
ansType = type(ans)
print(ans)
print(ansType)

#Two strings are anagrams if and only if their character counts (respective number of occurrences of each character) are the same.
##Frequency maps

class Solution:
def groupAnagramsFrequency(self, strs):
ans = collections.defaultdict(list)
for s in strs:
count = [0] * 26
print('count at s: ', count)
print('')
print(' ')
for c in s:
count[ord(c) - ord('a')] += 1
print("ord('a'): ", ord('a'))
print("ord(c): ", ord(c))
print('c - a: ', ord(c) - ord('a'))
print('count at c: ', count)
print(' ')
ans[tuple(count)].append(s)
print('s appended: ', s)
print('ans: ', ans)
print(' ')
print(' ')
return ans.values()

ans = Solution().groupAnagramsFrequency(strs)
ansType = type(ans)
print(ans)
print(ansType)


This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.