登录
首页 >  Golang >  Go问答

Go语言找出字符串中最长连续重复的字符

来源:stackoverflow

时间:2024-03-10 17:24:19 394浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《Go语言找出字符串中最长连续重复的字符》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

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

今天关于《Go语言找出字符串中最长连续重复的字符》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>