leetcode 1758

2021-04-08 12:35:41 +08:00
 yujianwjj

https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/

题目比较简单,只有 010101... 或者 101010... 两个方案 最开始我的解法是:

func minOperations(s string) int {
    count1 := 0
    // 010101...
    for i := 0; i < len(s); i++ {
        if int(s[i] - '0') != i % 2 {
            count1++
        }
    }
    count2 := 0
    // 10101010...
    for i := 0; i < len(s); i++ {
        if int(s[i] - '0') != (i+1) % 2 {
            count2++
        }
    }
    return min(count1, count2)
}

后来发现更简单一点的

func minOperations(s string) int {
    count1 := 0
    // 010101...
    for i := 0; i < len(s); i++ {
        if int(s[i] - '0') != i % 2 {
            count1++
        }
    }
    
    return min(count1, len(s)-count1)
}

我的疑问是如何用数学证明这两种方案加起来刚好是 s 的长度。

1841 次点击
所在节点    LeetCode
1 条回复
misdake
2021-04-08 12:53:15 +08:00
如果 S ^ A = 010101...
那 S ^ ~A = 101010...
A 和~A 互补,两个数中 1 的数量总和就是长度。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/769022

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX