LeetCode in Kotlin

2222. Number of Ways to Select Buildings

Medium

You are given a 0-indexed binary string s which represents the types of buildings along a street where:

As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type.

Return the number of valid ways to select 3 buildings.

Example 1:

Input: s = “001101”

Output: 6

Explanation: The following sets of indices selected are valid:

No other selection is valid. Thus, there are 6 total ways.

Example 2:

Input: s = “11100”

Output: 0

Explanation: It can be shown that there are no valid selections.

Constraints:

Solution

class Solution {
    fun numberOfWays(s: String): Long {
        var z: Long = 0
        var o: Long = 0
        var zo: Long = 0
        var oz: Long = 0
        var zoz: Long = 0
        var ozo: Long = 0
        for (c in s.toCharArray()) {
            if (c == '0') {
                zoz += zo
                oz += o
                z++
            } else {
                ozo += oz
                zo += z
                o++
            }
        }
        return zoz + ozo
    }
}