zoukankan      html  css  js  c++  java
  • 438. Find All Anagrams in a String

    package LeetCode_438
    
    /**
     * 438. Find All Anagrams in a String
     * https://leetcode.com/problems/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.
    Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
    The order of output does not matter.
    
    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".
     * */
    class Solution {
        /**
         * solution: Array+Sliding Window, Time complexity:O(n), Space complexity:O(26)
         * */
        fun findAnagrams(s: String, p: String): List<Int> {
            val result = ArrayList<Int>()
            val window = p.length
            val len = s.length
            if (window == 0 || len == 0) {
                return result
            }
            if (len < window) {
                return result
            }
            var left = 0
            var right = 0
            val hash = IntArray(26)
            val pHasp = IntArray(26)
            while (right < window) {
                hash[s[right] - 'a']++
                pHasp[p[right] - 'a']++
                right++
            }
            //scan remaining len of s
            while (right <= len) {
                if (pHasp contentEquals hash) {
                    result.add(left)
                }
                /*
                * keep tracking in window size,
                * for example: cbaebabacd,
                * next track: eba=>bab...
                * */
                if (right != len) {
                    hash[s[right] - 'a']++
                }
                right++
                hash[s[left++] - 'a']--
            }
            return result
        }
    }
  • 相关阅读:
    #include
    算法导论 Chapter 9.3 Selection in worstcase linear time
    算法导论 Exercises 9.36
    算法导论 Exercises 9.37
    C++实现Ping
    算法导论 Exercises 9.39
    如何计算毫秒级的时间差
    如何产生 [0, 2147483647] 之间的随机数
    算法导论 Exercises 9.38
    KMP算法学习&总结
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13168907.html
Copyright © 2011-2022 走看看