首頁 > 後端開發 > Golang > 主體

golang連續重複最長的字符

王林
發布: 2024-02-11 15:24:10
轉載
1064 人瀏覽過

golang連續重複最長的字符

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
}
登入後複製

//// 預期的 : {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! :)
登入後複製

以上是golang連續重複最長的字符的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!