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

相关推荐
千弥霜20 小时前
codeforces1914 C~F
c语言·算法
wyiyiyi20 小时前
【数据结构+算法】进栈顺序推算、卡特兰数与逆波兰表达式
汇编·数据结构·笔记·算法
天若有情67320 小时前
Multi-Stride Predictive RNG:革命性的可控随机数生成算法
算法·算法设计·c++编程·随机数生成·msp-rng·魔术算法
C_Liu_20 小时前
14:C++:二叉搜索树
算法
CC-NX21 小时前
32位汇编:实验9分支程序结构使用
汇编·算法·win32·分支结构
万岳科技系统开发21 小时前
外卖小程序中的高并发处理:如何应对大流量订单的挑战
算法·小程序·开源
TL滕21 小时前
从0开始学算法——第二天(时间、空间复杂度)
数据结构·笔记·学习·算法
旺仔老馒头.1 天前
【数据结构与算法】手撕排序算法(二)
c语言·数据结构·算法·排序算法
好学且牛逼的马1 天前
【Hot100 | 2 LeetCode49 字母异位词分组问题】
算法
2301_795167201 天前
Rust 在内存安全方面的设计方案的核心思想是“共享不可变,可变不共享”
算法·安全·rust