博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode Find All Anagrams in a String
阅读量:5080 次
发布时间:2019-06-12

本文共 2199 字,大约阅读时间需要 7 分钟。

原题链接在这里:

题目:

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:

1 public class Solution { 2     public List
findAnagrams(String s, String p) { 3 List
res = new ArrayList
(); 4 if(s == null || p == null || s.length() == 0 || p.length() == 0){ 5 return res; 6 } 7 int [] map = new int[256]; 8 for(int i = 0; i
0){16 //Move runner everytime. Decrease corresponding char count by 117 //If current char count is larger than 0, then this char is in p18 sum--;19 }20 21 if(sum == 0) {22 //Find anagram23 res.add(walker);24 }25 26 if(runner-walker == p.length() && map[s.charAt(walker++)]++ >= 0){27 //If windows's size is already p.length(), move walker and increase corresponding char count by 1 28 //If count before increasing is not smaller than 0, this char is in p29 sum++;30 }31 }32 return res;33 }34 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/6208421.html

你可能感兴趣的文章
PHP上传RAR压缩包并解压目录
查看>>
Codeforces 719B Anatoly and Cockroaches
查看>>
jenkins常用插件汇总
查看>>
c# 泛型+反射
查看>>
第九章 前后查找
查看>>
Python学习资料
查看>>
jQuery 自定义函数
查看>>
jquery datagrid 后台获取datatable处理成正确的json字符串
查看>>
ActiveMQ与spring整合
查看>>
web服务器
查看>>
网卡流量检测.py
查看>>
poj1981 Circle and Points 单位圆覆盖问题
查看>>
POP的Stroke动画
查看>>
SQL语句在查询分析器中可以执行,代码中不能执行
查看>>
yii 1.x 添加 rules 验证url数组
查看>>
html+css 布局篇
查看>>
SQL优化
查看>>
用C语言操纵Mysql
查看>>
轻松学MVC4.0–6 MVC的执行流程
查看>>
redis集群如何清理前缀相同的key
查看>>