简体   繁体   中英

Longest substring in which all bits are the same (DP algorithm)

You're given a bit string that consists of 1 <= n <= 32 bits.

You are also given a sequence of changes that invert some of the bits. If the original string is 001011, and the change is "3", then the changed bit string would be 000011. (The 3rd bit from the right was flipped)

I have to find after each change, the length of the longest substring in which each bit is the same. Therefore, for 000011, the answer would be 4.

I think brute force would just be a sliding window that starts at size of the string and shrinks until the first instance where all the bits in the window are the same.

How would that be altered for a dynamic programming solution?

You can solve this by maintaining a list of indices at which the bit flips. You start by creating that list: shift the sequence by one bit (losing the one on the end), and compare to the original. Any mismatch here is a bit flip. Make a list of those indices:

001011
01011
-234--

In this case, you have bit flips after locations 2, 3, and 4.

Now, you need to develop a simple function to process your change operation. This is very simple: for a change of bit n , you need to change whether indices n-1 and n are in the list: if it's not in the list, add it; if it is in the list, remove it. In the case of changing bit 3, both are in the list, so you now remove them:

---4--

Any time you want to check the longest substring, you need merely check adjacent indices for the largest different. Include 0 and the string length as endpoints. Thus, when you have the list [0, 2, 3, 4, 6], you have a maximum difference of 2 at 2-0 and 6-4. After the change, with the list [0, 4, 6], you have the maximum difference of 4 at 4-0.

If you have a large list with many indices, you can simply maintain differences, altering only the adjacent intervals affected by the single change.

This should get you going; I leave the implementation details to the student. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM