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)
推荐阅读
- LintCode|LintCode 545 [Top k Largest Number II]
- Android学习笔记|Chapter1:Gradle基础概念
- 快乐数|快乐数 (lintcode:happy-number)
- LintCode【简单】60. 搜索插入位置 。代码及思路
- 宏观经济学(1)
- LeetCode|Lintcode: Serialize and Deserialize Binary Tre & 剑指offer(序列化、反序列化二叉树)
- LintCode|LintCode 题目(转换成小写字母)
- LintCode刷题之路(七)(Serialize and Deserialize Binary Tree)
- LintCode 二叉树的序列化和反序列化 题解
- Chapter12_Advanced_Numpy