Go实现最长连续重复字符函数遇Codewars边界测试失败求助
问题排查:Codewars「Character with longest consecutive repetition」Go实现边界测试失败
问题场景
完成Codewars题目「Character with longest consecutive repetition」,Go语言实现LongestRepetition函数后,本地测试正常,但提交后无法通过边界测试。例如输入单字符或无重复多字符时,预期返回<kata.Result>: {C: 98, L: 1},实际返回<kata.Result>: {C: 0, L: 0}。
原实现代码
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 }
问题分析
- 未初始化max的初始状态:
max变量初始化为空Result(C=0, L=0),仅当字符连续重复时才会更新max。如果输入字符串中所有字符均为单次出现(如"ba"),循环中不会触发max的更新逻辑,最终返回初始空值。 - 冗余代码与逻辑漏洞:
- 单独处理
len(text)==1的分支虽能覆盖单字符场景,但多字符无重复场景未被覆盖。 count.C == s分支中count.C = s属于冗余操作,此时两者已相等。
- 单独处理
修正后的代码
package main import ( "fmt" ) type Result struct { C rune // character L int // count } func main() { fmt.Println(LongestRepetition("")) fmt.Println(LongestRepetition("b")) fmt.Println(LongestRepetition("ba")) fmt.Println(LongestRepetition("aaabbbcc")) } func LongestRepetition(text string) Result { if text == "" { return Result{} } // 初始化max为第一个字符的状态,覆盖单字符场景 max := Result{C: rune(text[0]), L: 1} count := max // count从第一个字符开始计数 // 从第二个字符开始遍历,简化逻辑 for _, s := range text[1:] { if count.C == s { count.L++ // 当前连续长度超过max时更新 if count.L > max.L { max = count } } else { // 重置count为当前字符的初始状态 count = Result{C: s, L: 1} } } return max }
优化建议
- 移除冗余分支:通过初始化
max为第一个字符的状态,无需单独处理len(text)==1的场景,简化代码结构。 - 简化遍历逻辑:从第二个字符开始遍历,避免循环内重复判断初始状态,提升代码可读性。
- 批量赋值:更新
max时直接赋值max = count,无需分别设置C和L,代码更简洁。
内容的提问来源于stack exchange,提问作者HeczZots
相关产品推荐
相关产品推荐

