ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Time Needed to Rearrange a Binary String

2022-08-21 16:32:43  阅读:205  来源: 互联网

标签:Binary 01 return becomes After Rearrange Needed second 字符串


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有