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:

1s.length1000
s[i] is either 0 or 1 .

 

解题思路

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

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

  因此最糟糕的情况是一个字符串前面部分都是0,后面剩下的部分都是1,比如000001111,那么操作的时间取决于最左边的第一个0,假设字符串前面有a0,后面有b1,那么最左边的0需要等待a1秒让a10往后跳,然后最左边的0还需要跳过b1,因此这种情况下需要操作a+b1秒。因此在最坏的情况下时间复杂度为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

posted @   onlyblues  阅读(50)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
Web Analytics
点击右上角即可分享
微信分享提示