具有最长连续重复Golang的字符

dhxwm5r4  于 2023-05-04  发布在  Go
关注(0)|答案(2)|浏览(132)
package main

import (
    "fmt"
)

type Result struct {
    C rune // character
    L int  // count
}

func main() {
    fmt.Print(LongestRepetition(""))
}
func LongestRepetition(text string) Result {
    if text == "" {
        return Result{}
    }
    var max Result
    if len(text) == 1 {
        max.C = rune(text[0])
        max.L = 1
        return max
    }
    var count Result
    for _, s := range text {
        if count.C == s {
            count.L++
            count.C = s
            if count.L > max.L {
                max.C = count.C

                max.L = count.L
            }
        } else {
            count.L = 1
            count.C = s
        }

    }
    return max
}

////预期<kata.Result>:{C:0,L:0}等于<kata.Result>:{C:98,L:1}
我试图完成https://www.codewars.com/kata/586d6cefbcc21eed7a001155/train/go字符与最长的连续重复我的测试它的工作正常,但当我推到CW它不能完成角落测试帮助我请可能是我可以改善我的代码somethere或东西im misted

disho6za

disho6za1#

你的解决方案太复杂了。简化。

func LongestRepetition(text string) Result {
    max := Result{}

    r := Result{}
    for _, c := range text {
        if r.C != c {
            r = Result{C: c}
        }
        r.L++

        if max.L < r.L {
            max = r
        }
    }

    return max
}
Time: 1737ms Passed: 2 Failed: 0
Test Results:
Fixed Tests
it should work with the fixed tests
Random Tests
it should work with the random tests
You have passed all of the tests! :)
qhhrdooz

qhhrdooz2#

您需要将用于更新max的逻辑从嵌套的if中移出,并将其移到循环迭代的末尾:

for _, s := range text {

    // ...

    if count.L > max.L {
        max = count
    }
}

这确保您不仅可以获得长时间重复的结果,还可以获得单个字母的结果。
https://go.dev/play/p/BLklmElS9Uv

相关问题