[LeetCode] Time Needed to Rearrange a Binary String

2380. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
bool check(string& s) {
bool pass = false;
for(int i = 0; i < s.length(); i++) {
if(pass and s[i] == '1') return true;
if(s[i] == '0') pass = true;
}
return false;
}
public:
int secondsToRemoveOccurrences(string s) {
int res = 0, cnt = 0;
while(check(s)) {
for(int i = 0; i < s.length() - 1; i++) {
if(s[i] == '0' and s[i + 1] == '1') {
swap(s[i],s[i+1]);
i += 1;
}
}
res++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/20/PS/LeetCode/time-needed-to-rearrange-a-binary-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.