zoukankan      html  css  js  c++  java
  • [LeetCode] 438. Find All Anagrams in a String(在字符串中寻找所有的相同字母异序词)

    Description

    Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
    给定一个字符串 s 和一个非空字符串 p,在 s 里寻找与 p 互为相同字母异序词的子串,返回这些子串的起始下标。

    Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
    所有字符串只包含小写英文字母,sp 的长度不超过 20,100。

    The order of output does not matter.
    可以以任意顺序输出结果。

    Examples

    Example 1

    Input:
    s: "cbaebabacd" p: "abc"
    
    Output:
    [0, 6]
    
    Explanation:
    The substring with start index = 0 is "cba", which is an anagram of "abc".
    The substring with start index = 6 is "bac", which is an anagram of "abc".
    

    Example 2

    Input:
    s: "abab" p: "ab"
    
    Output:
    [0, 1, 2]
    
    Explanation:
    The substring with start index = 0 is "ab", which is an anagram of "ab".
    The substring with start index = 1 is "ba", which is an anagram of "ab".
    The substring with start index = 2 is "ab", which is an anagram of "ab".
    

    Solution

    对于相同字母异序词,首先想到的就是统计字母出现的频率。本题解法显而易见:先统计 p 的字频,然后再统计 s 从 0 开始的子串的字频,然后维护一个长度为 p.length 的滑动窗口,维护其中的字频并与目标值进行比较。考虑到 HashMap 有映射不存在的问题难以处理,本题的字符串又只包含小写英文字母,所以直接使用长度为 26 的数组代替 HashMap,代码如下:

    class Solution {
        fun findAnagrams(s: String, p: String): List<Int> {
            // 没说 p 的长度一定比 s 小,所以需要判断
            if (s.length < p.length) {
                return emptyList()
            }
            val target = p.freqArray()
            val cur = IntArray(26)
            val result = arrayListOf<Int>()
            // 第一趟
            for (i in 0..p.lastIndex) {
                cur[s[i] - 'a']++
            }
            if (cur.contentEquals(target)) {
                result.add(0)
            }
            // 滑动窗口,每次往后移动一个字符,更新 cur 并与 target 比较
            for (i in 1..(s.lastIndex - p.lastIndex)) {
                cur[s[i - 1] - 'a']--
                cur[s[i + p.lastIndex] - 'a']++
                if (cur.contentEquals(target)) {
                    result.add(i)
                }
            }
            return result
        }
    
        private fun String.freqArray(): IntArray {
            val result = IntArray(26)
            this.forEach { result[it - 'a']++ }
            return result
        }
    }
    
  • 相关阅读:
    jqueryui 进度条使用
    第一阶段站立会议03
    第一阶段站立会议02
    第一阶段站立会议01
    找到了——电梯会议
    软件需求规格说明书
    团队项目计划会议
    软件开发团队简介
    找水王
    NABCD需求分析
  • 原文地址:https://www.cnblogs.com/zhongju/p/14040622.html
Copyright © 2011-2022 走看看