当前位置:网站首页>找到字符串中所有字母异位词
找到字符串中所有字母异位词
2022-07-21 18:38:00 【GreyZeng】
找到字符串中所有字母异位词
作者:Grey
原文地址:找到字符串中所有字母异位词
题目描述
主要思路
使用滑动窗口和欠账表的机制,首先,将p
串建立词频表
int c = pStr.length;
for (char ch : pStr) {
map[ch - 'a']++;
}
用于查询s
串中还欠p
串的元素种类和个数是多少。总共欠的字符个数是c
。
接下来建立滑动窗口,在s
串中设置l
和r
两个指针,先移动r
,如果r
位置的字符正好是p
中的字符,说明这是一次有效还款,则c--
,r
继续移动,如果每次都是有效还款,则c
必减为0
,此时,就可以收集答案了,当r - l
的长度正好是p
串的长度时候,则说明必须以l
位置的窗口,已经判断完毕了,接下来,可以移动l
指针,开始缩窗口。如果l
缩的位置正好是有效位置,则c++
(因为l
的旧位置已经不属于当前窗口了)。
时间复杂度O(N)
。
完整代码
public class LeetCode_0438_FindAllAnagramsInAString {
// 滑动窗口 + 欠账表
public List<Integer> findAnagrams(String s, String p) {
if (s == null || p == null) {
return new ArrayList<>();
}
List<Integer> ans = new ArrayList<>();
char[] str = s.toCharArray();
char[] pStr = p.toCharArray();
// 词频表
int[] map = new int[26];
// 窗口从[l,r)
int l = 0;
int r = 0;
// 欠账数量
int c = pStr.length;
for (char ch : pStr) {
map[ch - 'a']++;
}
int n = str.length;
while (r < n) {
if (map[str[r] - 'a'] > 0) {
// 有效还款
c--;
}
map[str[r++] - 'a']--;
if (c == 0) {
// 收集到一个位置
ans.add(l);
}
// 形成窗口
if (r - l == pStr.length) {
// l面临要出窗口
if (map[str[l] - 'a'] >= 0) {
// 退回去
c++;
}
map[str[l++] - 'a']++;
}
}
return ans;
}
}
类似问题
更多
边栏推荐
- JS type conversion
- The office mode of traditional enterprises is changing. Why do enterprises need digital office?
- Introduction to wechat applet routing
- Comment win10 envoie une icône au Bureau
- Win10如何把圖標發送到桌面
- 第三章第四节:形参
- 别闹了,想进大厂还不知道提升哪些方面的能力吗?(赶快收藏)
- opencv实现银行卡号识别
- mysql 事务操作与锁机制
- Section 1 of Chapter 3: concept of function
猜你喜欢
你第一篇SCI写了几个月?(第二部分)
黑马瑞吉外卖之过滤器后台登录验证(详细笔记说明)
Deploy the jar package of Ruiji takeout project on the remote server and successfully run on the PC and mobile terminal
VSCODE解决终端中文乱码的问题
【报错】ValueError: It seems that you are using the Keras 2 and you are passing both
融云超级群的「新能力」
Live broadcast preview │ special session of Zhihui Yunzhou "digital twin smart Park solutions"
解决API开发痛点,Apipost和Apifox哪个更好?
Section 20 of Chapter 2: operators one
互联网寒冬,3个月如何从功能测试进阶自动化测试?【附学习指南】
随机推荐
别闹了,想进大厂还不知道提升哪些方面的能力吗?(赶快收藏)
《机器人SLAM导航核心技术与实战》第1季:第1章_ROS入门必备知识
Section 20 of Chapter 2: operators one
abaqus 中英文转换
Introduction to wechat applet routing
Redis Client集成Prometheus指标
Section 3 of Chapter 3: parameter classification
video实现控制视频进度和播放、暂停
智能科学创新讲堂 | 自动化所何晖光: 基于视觉信息编解码的深度学习类脑机制研究
分享一个GO 辅助命令行
第三章 第三节:实参分类
[300 opencv routines] 234 Principal component analysis (PCA) for feature extraction
Section 22 of Chapter 2: document operation 1
Summer Challenge [FFH] NFC touches and pulls up any application without enterprise certification!
Section 16 of Chapter 2: Circular nesting of dictionaries
Self adaptive development of self defined navigation bar for wechat applet
解决API开发痛点,Apipost和Apifox哪个更好?
列表迭代器
华泰证券远程开户安全吗?有保障吗?
How 3D video fusion technology enables smart city construction