其他分享
首页 > 其他分享> > Time Needed to Rearrange a Binary String

Time Needed to Rearrange a Binary String

作者:互联网

Time Needed to Rearrange a Binary String

You are given a binary string $s$. In one second, all occurrences of 01 are simultaneously replaced with 10 . This process repeats until no occurrences of 01 exist.

Return the number of seconds needed to complete this process.

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.

Constraints:

$1 \leq s.length \leq 1000$
s[i] is either 0 or 1 .

 

解题思路

  比赛的时候直接模拟过的,事后来写题解证明模拟的做法是可以过的。

  模拟的过程就是把$01$变成$10$,本质是把$0$都往后面移。容易发现,对于一个$01$相间的字符串,如果把$0$都往前挪一些位,那么这个新的字符串所需要的时间一定不会比原来的字符串要少。

  因此最糟糕的情况是一个字符串前面部分都是$0$,后面剩下的部分都是$1$,比如$00000 \dots 1111$,那么操作的时间取决于最左边的第一个$0$,假设字符串前面有$a$个$0$,后面有$b$个$1$,那么最左边的$0$需要等待$a-1$秒让$a-1$个$0$往后跳,然后最左边的$0$还需要跳过$b$个$1$,因此这种情况下需要操作$a+b-1$秒。因此在最坏的情况下时间复杂度为$O(n)$。

  AC代码如下:

 1 class Solution {
 2 public:
 3     int secondsToRemoveOccurrences(string s) {
 4         int ret = 0;
 5         while (true) {
 6             bool flag = true;
 7             for (int i = 0; i + 1 < s.size(); i++) {
 8                 if (s[i] == '0' && s[i + 1] == '1') {
 9                     swap(s[i], s[i + 1]);
10                     i++;
11                     flag = false;
12                 }
13             }
14             if (flag) break;
15             ret++;
16         }
17         return ret;
18     }
19 };

 

参考资料

  力扣第85场双周赛:https://www.bilibili.com/video/BV1u14y1t771

标签:Binary,01,return,becomes,After,Rearrange,Needed,second,字符串
来源: https://www.cnblogs.com/onlyblues/p/16610198.html