An efficient algorithm for finding smallest pangrammatic windows?

前端 未结 2 738
一整个雨季
一整个雨季 2021-01-02 17:31

A pangrammatic window is a substring of a larger piece of text that contains all 26 letters of the alphabet. To quote an example from Wikipedia, given this

相关标签:
2条回答
  • 2021-01-02 17:44

    This algorithm has O(M) space complexity and O(N) time complexity (time does not depend on alphabet size M):

    1. Advance first iterator and increase counter for each processed letter. Stop when all 26 counters are non-zero.
    2. Advance second iterator and decrease counter for each processed letter. Stop when any of these counters is zero.
    3. Use difference between iterators to update best-so-far result and continue with step 1.

    This algorithm may be improved a little bit if instead of character counters, positions in the string are stored. In this case step 2 should only read these positions and compare with current position, and step 1 should update these positions and (most of the time) search for some character in the text.

    0 讨论(0)
  • 2021-01-02 18:01

    For every letter keep track of the recent-most sighting. Whenever you process a letter, update the corresponding sighting index and calculate the range (max-min) of sighting indexes over all letters. Find the location with minimum range.

    Complexity O(n). O(nlog(m)) if you consider alphabet size m.

    0 讨论(0)
提交回复
热议问题