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

相关推荐
wen__xvn1 小时前
每日一题洛谷P1914 小书童——凯撒密码c++
数据结构·c++·算法
BUG 劝退师2 小时前
八大经典排序算法
数据结构·算法·排序算法
m0_748240913 小时前
SpringMVC 请求参数接收
前端·javascript·算法
小林熬夜学编程3 小时前
【MySQL】第八弹---全面解析数据库表的增删改查操作:从创建到检索、排序与分页
linux·开发语言·数据库·mysql·算法
小小小白的编程日记3 小时前
List的基本功能(1)
数据结构·c++·算法·stl·list
_Itachi__3 小时前
LeetCode 热题 100 283. 移动零
数据结构·算法·leetcode
柃歌3 小时前
【UCB CS 61B SP24】Lecture 5 - Lists 3: DLLists and Arrays学习笔记
java·数据结构·笔记·学习·算法
鱼不如渔3 小时前
leetcode刷题第十三天——二叉树Ⅲ
linux·算法·leetcode
qwy7152292581633 小时前
10-R数组
python·算法·r语言
月上柳梢头&3 小时前
[C++ ]使用std::string作为函数参数时的注意事项
开发语言·c++·算法