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

本文共 2112 字,大约阅读时间需要 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".

 

用sliding window模板,保存结果的判断条件是fast - slow == p.length()

time: O(n), space: O(m)  -- n: length of s, m: length of p

class Solution {        public List
findAnagrams(String s, String p) { List
res = new ArrayList<>(); if(s.length() == 0 || s.length() < p.length()) { return res; } Map
map = new HashMap<>(); for(char c : p.toCharArray()){ map.put(c, map.getOrDefault(c, 0) + 1); } int counter = map.size(), slow = 0, fast = 0; while(fast < s.length()) { char c = s.charAt(fast); if(map.containsKey(c)) { map.put(c, map.get(c) - 1); if(map.get(c) == 0) { counter--; } } fast++; while(counter == 0) { char tempc = s.charAt(slow); if(map.containsKey(tempc)) { map.put(tempc, map.get(tempc) + 1); if(map.get(tempc) > 0) { counter++; } } if(fast - slow == p.length()) { res.add(slow); } slow++; } } return res; }}

 

转载于:https://www.cnblogs.com/fatttcat/p/10302104.html

你可能感兴趣的文章
mysql 加快 查询速度 索引
查看>>
bind nsupdate
查看>>
Google Map Api V3 系列之 Polygon 获取中心点方法
查看>>
显示SQL
查看>>
vue table内修改内容
查看>>
oracle远程连接配置
查看>>
POJ 1631 Bridging signals(LIS的等价表述)
查看>>
Android开发学习——ListView+BaseAdapter的使用
查看>>
hbase基础shell操作
查看>>
黑马程序员_java 内部类
查看>>
mongoDB 文档操作_增
查看>>
使用Installutil安装系统服务方法
查看>>
jQuery源码
查看>>
[Angularjs]asp.net mvc+angularjs+web api单页应用之CRUD操作
查看>>
c# 6.0新特性(二)
查看>>
[工具]json转类
查看>>
杭电 1231 最大连续子序列
查看>>
es7 --- 新特性
查看>>
[转载] 老友记——潘石屹 任志强《天台论道》(下)
查看>>
276. Paint Fence
查看>>