【Hot100】LeetCode—438. 找到字符串中所有字母异位词

目录

  • [1- 思路](#1- 思路)
    • [哈希表 + 滑动窗口](#哈希表 + 滑动窗口)
  • [2- 实现](#2- 实现)
    • [⭐438. 找到字符串中所有字母异位词------题解思路](#⭐438. 找到字符串中所有字母异位词——题解思路)
  • [3- ACM 实现](#3- ACM 实现)


1- 思路

哈希表 + 滑动窗口

思路

  • 哈希表:通过数组维护一个哈希表
  • 滑动窗口:通过控制数组的下标,来实现滑动窗口

2- 实现

⭐438. 找到字符串中所有字母异位词------题解思路

java 复制代码
class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        //1. 数据结构
        List<Integer> res = new ArrayList<>();
        int[] sHash = new int[26];
        int[] pHash = new int[26];
        int sLen = s.length();
        int pLen = p.length();

        if(sLen<pLen){
            return res;
        }

        // 2.首次遍历
        for(int i = 0 ; i < pLen;i++){
            sHash[s.charAt(i)-'a']++;
            pHash[p.charAt(i)-'a']++;
        }
        if(Arrays.equals(sHash,pHash)){
            res.add(0);
        }

        // 3.循环遍历
        for(int i = 0; i <sLen-pLen;i++){
            // 3.1左侧维护
            sHash[s.charAt(i)-'a']--;
            sHash[s.charAt(pLen+i)-'a']++;
            if(Arrays.equals(sHash,pHash)){
                res.add(i+1);
            }
        }
        return res;
    }
}

3- ACM 实现

java 复制代码
public class findAnagrams {

    public static List<Integer> findA(String s,String p){
        //1. 数据结构
        List<Integer> res = new ArrayList<>();
        int[] sCount = new int[26];
        int[] pCount = new int[26];
        int sLen = s.length();
        int pLen = p.length();

        if(sLen<pLen){
            return res;
        }
        // 2.首次遍历
        for(int i = 0 ; i < pLen;i++){
            sCount[s.charAt(i)-'a']++;
            pCount[p.charAt(i)-'a']++;
        }
        if(Arrays.equals(sCount,pCount)){
            res.add(0);
        }

        // 3.再次遍历
        for(int i =0;i<sLen-pLen;i++){
            sCount[s.charAt(i)-'a']--;
            sCount[s.charAt(i+pLen)-'a']++;
            if(Arrays.equals(sCount,pCount)){
                res.add(i+1);
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("输入字符串1");
        String str1 = sc.nextLine();
        System.out.println("输入字符串2");
        String str2 = sc.nextLine();

        System.out.println("结果是"+findA(str1,str2));
    }
}

相关推荐
iuu_star23 分钟前
C语言数据结构-顺序查找、折半查找
c语言·数据结构·算法
Yzzz-F30 分钟前
P1558 色板游戏 [线段树 + 二进制状态压缩 + 懒标记区间重置]
算法
漫随流水37 分钟前
leetcode算法(515.在每个树行中找最大值)
数据结构·算法·leetcode·二叉树
mit6.8241 小时前
dfs|前后缀分解
算法
扫地的小何尚2 小时前
NVIDIA RTX PC开源AI工具升级:加速LLM和扩散模型的性能革命
人工智能·python·算法·开源·nvidia·1024程序员节
千金裘换酒3 小时前
LeetCode反转链表
算法·leetcode·链表
byzh_rc4 小时前
[认知计算] 专栏总结
线性代数·算法·matlab·信号处理
qq_433554544 小时前
C++ manacher(求解回文串问题)
开发语言·c++·算法
歌_顿4 小时前
知识蒸馏学习总结
人工智能·算法
圣保罗的大教堂4 小时前
leetcode 1161. 最大层内元素和 中等
leetcode