博客
关于我
【滑动窗口法】—— 438. 找到字符串中所有字母异位词
阅读量:362 次
发布时间:2019-03-04

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

题目描述

给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。

字符串只包含小写英文字母,并且字符串 s 和 p 的长度都不超过 20100。

说明:

字母异位词指字母相同,但排列不同的字符串。

不考虑答案输出的顺序。
示例 1:

输入:

s: “cbaebabacd” p: “abc”

输出:

[0, 6]

解释:

起始索引等于 0 的子串是 “cba”, 它是 “abc” 的字母异位词。
起始索引等于 6 的子串是 “bac”, 它是 “abc” 的字母异位词。
示例 2:

输入:

s: “abab” p: “ab”

输出:

[0, 1, 2]

解释:

起始索引等于 0 的子串是 “ab”, 它是 “ab” 的字母异位词。
起始索引等于 1 的子串是 “ba”, 它是 “ab” 的字母异位词。
起始索引等于 2 的子串是 “ab”, 它是 “ab” 的字母异位词。

解题思路

class Solution_438 {       public List
findAnagrams(String s, String p) { //对p串的每个字符进行hash计数 int pLength = p.length(); int sLength = s.length(); int[] counts = new int[26]; for (int i = 0; i < pLength; i++) { counts[p.charAt(i) - 'a']++; } ArrayList
res = new ArrayList<>(); //从下标为0开始遍历字符串s,对于每个下标,判断接下来长度为pLength的子串是否为目标串的字母异位词 for (int i = 0; i <= sLength - pLength; i++) { //判断过程为临时拷贝一份新的技术数组 int[] tempCounts = Arrays.copyOf(counts,26); int j = i; //内部每次遍历p的长度个数的子串,把子串中每个字符的计数器减一,出现负数则进入下个子串的统计 for(;j < sLength && j < pLength + i;j++){ if (--tempCounts[s.charAt(j) - 'a'] < 0){ break; } } if (j >= pLength + i){ res.add(i); } } return res; }}

转载地址:http://vser.baihongyu.com/

你可能感兴趣的文章
nmap 使用方法详细介绍
查看>>
Nmap扫描教程之Nmap基础知识
查看>>
nmap指纹识别要点以及又快又准之方法
查看>>
Nmap渗透测试指南之指纹识别与探测、伺机而动
查看>>
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>