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