Finding a substring, with some additional conditions

后端 未结 3 1294
太阳男子
太阳男子 2021-02-03 13:53

I\'m given a string which looks like this:

1011010100

And my task is to find the length of a substring which number of nulls is always <= nu

3条回答
  •  没有蜡笔的小新
    2021-02-03 14:30

    (Almost correct, i.e. subtly wrong) linear time solution

    with two recodings of the problem (one removed later...), and a sliding window.

    Encoding A

    You can compress the input to yield the number of subsequent zeros or ones:

    +1 -1 +2 -1 +1 -1 +1 -2

    This yields encoding A and needs O(n) time.

    Encoding B

    Now, in encoding A, whenever you encounter two consecutive numbers that sum up to > 0, you compress further. In encoding B, the number in parentheses denotes the length of the substring:

    +2(4) -1 +1 -1 +1 -2 ==> +2(6) -1 +1 -2 ==> +2(8) -2

    This requires O(n), too. Here, we have the solution immediately: A string of length 8 with two more 1's than 0's. Let's try a more complicated instance (given in encoding A):

    +5 -8 +4

    Here, the transformation to encoding B doesn't help:

    +5(5) -8 +4(4)

    Consider also the following instance (encoding B):

    +5(9) -6 +4(4) -6 +5(7) -6 +4(6) -6 +5(9)

    This sequence will be used to demonstrate the...

    Sliding window

    First, determine the best solution that starts at the left:

    +5 -6 +4 -6 +5 > 0 ==> 9+6+4+6+7=32

    Now, extend this to find the best solution that starts at the third position (+4(4)):

    +4 -6 +5 -6 +4 > 0 ==> 4+6+7+6+6=29

    This solution is not better than the first we have found. Move on:

    +5 -6 +4 -6 +5 > 0 ==> 7+6+6+6+9=34

    This is the best solution. The algorithm can be implemented in O(n), since head and tail move only forward.

    The brief description above doesn't cover all subtleties (negative number at the left in encoding B, head and tail meet, ...). Also, perhaps the recodings are unnecessary and the sliding window can be implemented directly on the 0-1 representation. However, I was able to fully understand the problem only after recoding it.

    Getting rid of encoding B

    Actually as kindly noted by Millie Smith, "encoding B" might be lossy, meaning that it might lead to inferior solutions in certain (yet to be identified) corner cases. But the sliding window algorithm works just as well on encoding A, so it might be even necessary to skip the conversion to encoding B. (Too lazy to rewrite the explanation of the algorithm...)

提交回复
热议问题