博客
关于我
【滑动窗口法】—— 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/

你可能感兴趣的文章
Nginx
查看>>
nginx + etcd 动态负载均衡实践(一)—— 组件介绍
查看>>
nginx + etcd 动态负载均衡实践(三)—— 基于nginx-upsync-module实现
查看>>
nginx + etcd 动态负载均衡实践(二)—— 组件安装
查看>>
nginx + etcd 动态负载均衡实践(四)—— 基于confd实现
查看>>
Nginx + Spring Boot 实现负载均衡
查看>>
Nginx + Tomcat + SpringBoot 部署项目
查看>>
Nginx + uWSGI + Flask + Vhost
查看>>
Nginx - Header详解
查看>>
nginx - thinkphp 如何实现url的rewrite
查看>>
Nginx - 反向代理、负载均衡、动静分离、底层原理(案例实战分析)
查看>>
Nginx - 反向代理与负载均衡
查看>>
nginx 1.24.0 安装nginx最新稳定版
查看>>
nginx 301 永久重定向
查看>>
nginx connect 模块安装以及配置
查看>>
nginx css,js合并插件,淘宝nginx合并js,css插件
查看>>
Nginx gateway集群和动态网关
查看>>
nginx http配置说明,逐渐完善。
查看>>
Nginx keepalived一主一从高可用,手把手带你一步一步配置!
查看>>
Nginx Location配置总结
查看>>