LintCode_chapter1_section4_anagrams

coding = utf-8 '''
Created on 2015年11月5日
@author: SphinxW
'''
乱序字符串
给出一个字符串数组S,找到其中所有的乱序字符串(Anagram)。如果一个字符串是乱序字符串,那么他存在一个字母集合相同,但顺序不同的字符串也在S中。
您在真实的面试中是否遇到过这个题?
样例
对于字符串数组 ["lint","intl","inlt","code"]
返回 ["lint","inlt","intl"]
注意
【LintCode_chapter1_section4_anagrams】所有的字符串都只包含小写字母

class Solution: # @param strs: A list of strings # @return: A list of stringsdef anagrams(self, strs): # write your code here countStrs = {} result = [] for index, item in enumerate(strs): countItem = self.countChars(item) try: if index not in countStrs[countItem]: countStrs[countItem].append(index) except KeyError: countStrs[countItem] = [index, ] for key, item in countStrs.items(): if len(item) > 1: for s in item: result.append(strs[s]) return resultdef anagram(self, s, t): countsS = self.countChars(s) countsT = self.countChars(t) return countsS == countsTdef countChars(self, stringToCount): result = [] for item in range(ord("z") - ord("A")+1): result.append(0) for item in stringToCount: result[ord(item) - ord("A")] += 1 return str(result)

    推荐阅读