原题链接在这里:https://leetcode.com/problems/find-all-anagrams-in-a-string/

题目:

Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.

Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.

The order of output does not matter.

Example 1:

Input:
s: "cbaebabacd" p: "abc" Output:
[0, 6] Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".

Example 2:

Input:
s: "abab" p: "ab" Output:
[0, 1, 2] Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab". 

题解:

先将p的所有char对应的map count++.

然后快慢指针维护一个sliding window. 右侧runner每次都移动,对应的char的count减1. 若是count减1之前大于0, 表示char在p中, sum--.

sum为0时就找到了anagram.

当window大小为p长度时,移动左侧walker, 对应char的count加1. 若是count加1之前不是负数,表示这个char在p中, sum++.

Time Complexity: O(n). n = s.length().

Space: O(1). 用到了map.

AC Java:

 public class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> res = new ArrayList<Integer>();
if(s == null || p == null || s.length() == 0 || p.length() == 0){
return res;
}
int [] map = new int[256];
for(int i = 0; i<p.length(); i++){
map[p.charAt(i)]++;
}
int walker = 0;
int runner = 0;
int sum = p.length();
while(runner < s.length()){
if(map[s.charAt(runner++)]-- > 0){
//Move runner everytime. Decrease corresponding char count by 1
//If current char count is larger than 0, then this char is in p
sum--;
} if(sum == 0) {
//Find anagram
res.add(walker);
} if(runner-walker == p.length() && map[s.charAt(walker++)]++ >= 0){
//If windows's size is already p.length(), move walker and increase corresponding char count by 1
//If count before increasing is not smaller than 0, this char is in p
sum++;
}
}
return res;
}
}

类似Permutation in String.

最新文章

  1. C#实现在图片上斜着写字
  2. RHEL6解决无法使用YUM源问题
  3. mysql 线程池 数据库连接池
  4. 为什么SSL证书流量暴增?
  5. Struts学习之模型驱动
  6. C++中,引用作为函数参数
  7. JDBC连接数据库 prepareStatement
  8. SpringCloud学习笔记(1)——Eureka
  9. 【转载】MySQL之权限管理
  10. .NET框架(转)
  11. python中类似三元表达式的写法
  12. CentOS6.5安装与配置Mysql数据库
  13. Django复习之ORM
  14. springboot程序无法访问静态资源
  15. Java处理微信公众号文章图片不显示微信
  16. 装饰器中的@functools.wraps的作用
  17. 【读书笔记】iOS-网络-使用Game Kit实现设备间通信
  18. InteliJ Idea pom.xml不自动提示的解决
  19. 1-2 Mobx 入门实践之TodoList(官方Demo)
  20. 20155307 《Java程序设计》课堂实践项目MyOD

热门文章

  1. python之常用内置函数
  2. sqlserver 行列转换
  3. Java基本数据类型与位运算
  4. AgileEAS.NET SOA 中间件平台5.2版本下载、配置学习(一):下载平台并基于直连环境运行
  5. 微信扫描打开APP下载链接提示代码优化(转)
  6. Java基础知识点1:基本类型包装类
  7. oracle 资源学习汇总
  8. vs发布的程序不依赖运行时库msvcp100.dll
  9. Leetcode Anagrams
  10. myeclipse2014