
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
}//// 预期的 <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! :)
以上就是golang连续重复最长的字符的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号