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
        }
    }
  • 相关阅读:
    Leo程序员羊皮卷文摘(更新ing)
    ubuntu下的yuv播放器
    浏览器之一
    海量数据处理常用思路和方法(zh)
    我本将心向明月,奈何明月照沟渠
    转载光纤通信之父
    重装系统或是更换电脑之后,Foxmail的恢复
    关于录制Linux视频
    Linux之路(原发表于07年,现在搬到博客)
    Gentoo安装 miniCD+stage3
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13168907.html
Copyright © 2011-2022 走看看