#2380

Time Needed to Rearrange a Binary String

specialist · 845 · lc medium +31 · verified · 52.7% accepted · 551 likes · top 43%

Description

Given a binary string s, every second all adjacent "01" substrings are simultaneously replaced by "10". This continues until no "01" remains.

Return how many seconds the process takes to terminate.

Example 1:

Input: s = "0110101"
Output: 4
Explanation:
After one second, s becomes "1011010".
After another second, s becomes "1101100".
After the third second, s becomes "1110100".
After the fourth second, s becomes "1111000".
No occurrence of "01" exists any longer, and the process needed 4 seconds to complete,
so we return 4.

Example 2:

Input: s = "11100"
Output: 0
Explanation:
No occurrence of "01" exists in s, and the processes needed 0 seconds to complete,
so we return 0.

Code

1
2
3