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
        }
    }
  • 相关阅读:
    二逼平衡树(树套树)
    NOI2010 超级钢琴
    SDOI2011 消耗战
    HNOI2013 游走
    [SDOI2010]外星千足虫
    [UVA 11374]Airport Express
    [Luogu P1354]房间最短路问题
    [Luogu P2296][NOIP 2014]寻找道路
    高精度算法
    洛谷红名+AC150祭
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13168907.html
Copyright © 2011-2022 走看看