php小编百草为您介绍一种有趣的问题解决方法——“golang连续重复最长的字符”。这个问题的核心是找到一个字符串中连续出现次数最多的字符及其数量。在Golang中,我们可以通过遍历字符串的每个字符,并使用计数器和最大值变量来实现这个功能。通过这种简单而高效的算法,我们可以轻松解决这个问题,并得到准确的结果。接下来,让我们一起来了解具体的实现过程吧!
问题内容
package mainimport ( "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.lTime: 1737ms Passed: 2 Failed: 0Test Results:Fixed Testsit should work with the fixed testsRandom Testsit should work with the random testsYou have passed all of the tests! :)登录后复制
以上就是golang连续重复最长的字符的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2483817.html