Using a temporary wild card

This problem should be more in the easy category. The only caveat is to use a temporary wild card to do the first transform, then use it again for the second one. Can be solved in four lines. Code is down below, cheers, ACC.

Time Needed to Rearrange a Binary String - LeetCode

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 <= s.length <= 1000
  • s[i] is either '0' or '1'.

public class Solution {
    public int SecondsToRemoveOccurrences(string s)
    {
        int retVal = 0;
        while (s.Contains("01") && (++retVal > 0))
            s = s.Replace("01", "*").Replace("*", "10");
        return retVal;
    }
}

Comments

Popular posts from this blog

Advent of Code - Day 6, 2024: BFS and FSM

Golang vs. C#: performance characteristics (simple case study)

Advent of Code - Day 7, 2024: Backtracking and Eval