shortest digest of a string

Posted by meta on Stack Overflow See other posts from Stack Overflow or by meta
Published on 2010-03-03T09:54:31Z Indexed on 2010/03/25 2:43 UTC
Read the original article Hit count: 495

Filed under:
|

[Description] Given a string of char type, find a shortest digest, which is defined as: a shortest sub-string which contains all the characters in the original string.

[Example]

A = "aaabedacd"

B = "bedac" is the answer.

[My solution]

  1. Define an integer table with 256 elements, which is used to record the occurring times for each kind of character in the current sub-string.

  2. Scan the whole string, statistic the total kinds of character in the given string by using the above table.

  3. Use two pointers, start, end, which are initially pointing to the start and (start + 1) of the given string. The current kinds of character is 1.

  4. Expand sub-string[start, end) at the end until it contains all kinds of character. Update the shortest digest if possible.

  5. Contract sub-string[start, end] at the start by one character each time, try to restore its digest property if necessary by step 4.

The time cost is O(n), and the extra space cost is constant.

Any better solution without extra space?

© Stack Overflow or respective owner

Related posts about algorithm

Related posts about interview