卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35365本站已运行395

golang连续重复最长的字符

golang连续重复最长的字符

php小编百草为您介绍一种有趣的问题解决方法——“golang连续重复最长的字符”。这个问题的核心是找到一个字符串中连续出现次数最多的字符及其数量。在Golang中,我们可以通过遍历字符串的每个字符,并使用计数器和最大值变量来实现这个功能。通过这种简单而高效的算法,我们可以轻松解决这个问题,并得到准确的结果。接下来,让我们一起来了解具体的实现过程吧!

问题内容

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
}

//// 预期的 : {c: 0, l: 0} 等于 : {c: 98, l: 1}

我正在尝试完成https://www.codewars.com/kata/586d6cefbcc21eed7a001155/train/go 最长连续重复的字符 对于我的测试它工作正常 但当我推向 cw 时,它无法完成弯道测试 请帮助我 也许我可以在某处改进我的代码或我迷惑的东西

解决方法

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

type result struct {
    c rune // character
    l int  // count
}

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! :)

卓越飞翔博客
上一篇: Github 发布 golang 子模块
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏