Time Needed to Rearrange a Binary String
Time Needed to Rearrange a Binary String
You are given a binary string . 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:
s[i] is either 0 or 1 .
解题思路
比赛的时候直接模拟过的,事后来写题解证明模拟的做法是可以过的。
模拟的过程就是把变成,本质是把都往后面移。容易发现,对于一个相间的字符串,如果把都往前挪一些位,那么这个新的字符串所需要的时间一定不会比原来的字符串要少。
因此最糟糕的情况是一个字符串前面部分都是,后面剩下的部分都是,比如,那么操作的时间取决于最左边的第一个,假设字符串前面有个,后面有个,那么最左边的需要等待秒让个往后跳,然后最左边的还需要跳过个,因此这种情况下需要操作秒。因此在最坏的情况下时间复杂度为。
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
本文来自博客园,作者:onlyblues,转载请注明原文链接:https://www.cnblogs.com/onlyblues/p/16610198.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效