LeetCode100122. Separate Black and White Balls

一、题目

There are n balls on a table, each ball has a color black or white.

You are given a 0-indexed binary string s of length n, where 1 and 0 represent black and white balls, respectively.

In each step, you can choose two adjacent balls and swap them.

Return the minimum number of steps to group all the black balls to the right and all the white balls to the left.

Example 1:

Input: s = “101”
Output: 1
Explanation: We can group all the black balls to the right in the following way:

  • Swap s[0] and s[1], s = “011”.
    Initially, 1s are not grouped together, requiring at least 1 step to group them to the right.
    Example 2:

Input: s = “100”
Output: 2
Explanation: We can group all the black balls to the right in the following way:

  • Swap s[0] and s[1], s = “010”.
  • Swap s[1] and s[2], s = “001”.
    It can be proven that the minimum number of steps needed is 2.
    Example 3:

Input: s = “0111”
Output: 0
Explanation: All the black balls are already grouped to the right.

Constraints:

1 <= n == s.length <= 105
s[i] is either ‘0’ or ‘1’.

二、题解

class Solution {
public:
    long long minimumSteps(string s) {
        int n = s.length();
        //记录0的位置
        vector<int> zeroIndex;
        for(int i = 0;i < n;i++){
            if(s[i] == '0') zeroIndex.push_back(i);
        }
        long long res = 0;
        int front = 0;
        for(int i = 0;i < zeroIndex.size();i++){
            res += zeroIndex[i] - front;
            front++;
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值