首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >[LeetCode]Find All Anagrams in a String

[LeetCode]Find All Anagrams in a String

作者头像
全栈程序员站长
发布2022-07-19 13:41:39
发布2022-07-19 13:41:39
4170
举报

大家好,又见面了,我是全栈君。

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.

代码语言:javascript
复制
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".

1.解题思路

anagrams,就是只顺序不同但个数相同的字符串,那我们就可以利用hashtable的思想来比较每个字符串中字符出现的个数是否相等。 对于两个字符串我们分别准备数组(大小为256)来存储每个字符出现的次数: 1) 对于p,我们遍历,并在hp中记录字符出现的次数; 2) 之后遍历s,先把当前字符的个数+1,但是需要考虑当前index是否已经超过了p的长度,如果超过,则表示前面的字符已经不予考虑,所以要将index-plen的字符的个数-1;最后判断两个数组是否相等,如果相等,返回index-plen+1,即为开始的下标。

2.代码

代码语言:javascript
复制
public class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> res=new ArrayList<Integer>();
        if(s.length()==0||s==null||p.length()==0||p==null) return res;
        int[] hs=new int[256];
        int[] hp=new int[256];
        int plen=p.length();
        for(int i=0;i<plen;i++){
            hp[p.charAt(i)]++;
        }
        for(int j=0;j<s.length();j++){
            hs[s.charAt(j)]++;
            if(j>=plen){
                hs[s.charAt(j-plen)]--;
            }
            if(Arrays.equals(hs,hp))
                res.add(j-plen+1);
        }
        return res;
    }
}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/108772.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年2月2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档