Find All Anagrams in a String
来源:互联网 发布:centos samba 配置 编辑:程序博客网 时间:2024/06/08 03:39
题目详情:https://leetcode.com/problems/find-all-anagrams-in-a-string/description/
超时了好几次,终于做对了。
# -*- coding:utf-8 -*-class Solution(object): def findAnagrams(self, s, p): """ :type s: str :type p: str :rtype: List[int] """ result=[] #用来存储结果 i=0 #遍历开始的下标 slength,plength=len(s),len(p) #得到两者的长度 while i < slength: print i if self.detectAnagram(s,p,i) == True: #检测从i开始的,plength个元素是否为Anagram result.append(i) #是的话,添加到result中 #以下为改变下标i if i+plength<slength and s[i+plength] not in p:#比如:s='abceabc',p='abc' i=i+plength+1 #那么直接将i改为i+plength+1,因为e不在p中,i只要小于i+plength+1都不会相等 elif i+plength<slength and s[i]==s[i+plength]:#该条主要判断s中有循环的情况,比如: i+=1#s="abcdabcdabcdabcdabcd",p="abcd";处理这种情况,依次将i往后移,并添加到result中 while i+plength<slength and s[i]==s[i+plength]: #直到i+plength<slength或者s[i]==s[i+plength] result.append(i) #两者之一不满足,退出循环 i+=1 elif i+plength>slength: #这条判断s从位置i开始不能取plength个元素了,那么直接结束 break else: #其余情况简单的将i加1 i=i+1 return result def detectAnagram(self,s,p,pos): temp=s[pos:pos+len(p)] #取得从pos到pos+len(p)之间的元素,不包括pos+len(p)位置上元素 if set(temp)!=set(p) or len(temp)!=len(p): #如果把重复元素去掉之后,长度不相等或者 return False #不去重两者的长度就不相等,那么直接返回False值 for e in set(temp): #元素去重,并依次取出里面的元素 if temp.count(e)!=p.count(e) : #如果某一元素在temp和p中的个数不相等 return False#返回false值 return True#执行到这,说明是Anagram
阅读全文
0 0
- 438. Find All Anagrams in a String
- 438. Find All Anagrams in a String
- LeetCode Find All Anagrams in a String
- 438. Find All Anagrams in a String
- leetcode: Find All Anagrams in a String
- leetcode438. Find All Anagrams in a String
- leetcode438. Find All Anagrams in a String
- 438. Find All Anagrams in a String
- 438. Find All Anagrams in a String
- [LeetCode]Find All Anagrams in a String
- Find All Anagrams in a String
- LeetCode438 Find All Anagrams in a String
- 438. Find All Anagrams in a String
- Leetcode Find All Anagrams in a String
- 438. Find All Anagrams in a String
- 438. Find All Anagrams in a String
- 438. Find All Anagrams in a String*
- 438. Find All Anagrams in a String
- 《高质量 C++/C 编程指南 》阅读笔记(二)
- 0811 钟 区间第K大(kth)
- Eclipse快捷键大全
- XYNUOJ 问题 H: 统计难题
- c#键盘钩子全解
- Find All Anagrams in a String
- Vue—cli VUE官方提供的脚手架工具
- 键盘录入一个文件夹路径,统计该文件夹(包含子文件夹)中每种类型的文件及个数
- Shiro
- 在Windows下 python2.7安装scrapy
- c#进程操作-sendmessage全解
- 【SSLGZ 2674】2017年8月9日提高组T2 覆盖
- CSS3+js 简易时钟
- 阿里云ECS管理实操