【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));
    }
}

相关推荐
JieE21238 分钟前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
JieE2121 天前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack201 天前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树1 天前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE2122 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2122 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术2 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦2 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
用户497863050732 天前
(一)小红的数组操作
算法·编程语言