返回介绍

solution / 1500-1599 / 1529.Minimum Suffix Flips / README_EN

发布于 2024-06-17 01:03:18 字数 3592 浏览 0 评论 0 收藏 0

1529. Minimum Suffix Flips

中文文档

Description

You are given a 0-indexed binary string target of length n. You have another binary string s of length n that is initially set to all zeros. You want to make s equal to target.

In one operation, you can pick an index i where 0 <= i < n and flip all bits in the inclusive range [i, n - 1]. Flip means changing '0' to '1' and '1' to '0'.

Return _the minimum number of operations needed to make _s_ equal to _target.

 

Example 1:

Input: target = "10111"
Output: 3
Explanation: Initially, s = "00000".
Choose index i = 2: "00000" -> "00111"
Choose index i = 0: "00111" -> "11000"
Choose index i = 1: "11000" -> "10111"
We need at least 3 flip operations to form target.

Example 2:

Input: target = "101"
Output: 3
Explanation: Initially, s = "000".
Choose index i = 0: "000" -> "111"
Choose index i = 1: "111" -> "100"
Choose index i = 2: "100" -> "101"
We need at least 3 flip operations to form target.

Example 3:

Input: target = "00000"
Output: 0
Explanation: We do not need any operations since the initial s already equals target.

 

Constraints:

  • n == target.length
  • 1 <= n <= 105
  • target[i] is either '0' or '1'.

Solutions

Solution 1

class Solution:
  def minFlips(self, target: str) -> int:
    ans = 0
    for v in target:
      if (ans & 1) ^ int(v):
        ans += 1
    return ans
class Solution {
  public int minFlips(String target) {
    int ans = 0;
    for (int i = 0; i < target.length(); ++i) {
      int v = target.charAt(i) - '0';
      if (((ans & 1) ^ v) != 0) {
        ++ans;
      }
    }
    return ans;
  }
}
class Solution {
public:
  int minFlips(string target) {
    int ans = 0;
    for (char c : target) {
      int v = c - '0';
      if ((ans & 1) ^ v) {
        ++ans;
      }
    }
    return ans;
  }
};
func minFlips(target string) int {
  ans := 0
  for _, c := range target {
    v := int(c - '0')
    if ((ans & 1) ^ v) != 0 {
      ans++
    }
  }
  return ans
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文