Go语言找出字符串中最长连续重复的字符
时间:2024-03-10
浏览: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
}
//// 预期的 <kata.result>: {c: 0, l: 0} 等于 <kata.result>: {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学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
站内热门
最新文章
12.01
12.01
热门专题
