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

相关推荐
Yingjun Mo21 分钟前
1. 统计推断-基于神经网络与Langevin扩散的自适应潜变量建模与优化
人工智能·神经网络·算法·机器学习·概率论
地平线开发者1 小时前
征程 6 | 灰度图部署链路介绍
算法·自动驾驶
地平线开发者1 小时前
手撕大模型|KVCache 原理及代码解析
算法·自动驾驶
共享家95272 小时前
经典动态规划题解
算法·leetcode·动态规划
Pluchon2 小时前
硅基计划3.0 Map类&Set类
java·开发语言·数据结构·算法·哈希算法·散列表
☼←安于亥时→❦3 小时前
PyTorch之张量创建与运算
人工智能·算法·机器学习
子豪-中国机器人3 小时前
枚举算法和排序算法能力测试
开发语言·c++·算法
qiuyunoqy3 小时前
基础算法之二分算法 --- 2
算法
1白天的黑夜14 小时前
栈-844.比较含退格的字符串-力扣(LeetCode)
c++·leetcode·
爱干饭的boy4 小时前
手写Spring底层机制的实现【初始化IOC容器+依赖注入+BeanPostProcesson机制+AOP】
java·数据结构·后端·算法·spring