Home  >  Article  >  Backend Development  >  golang repeats the longest character continuously

golang repeats the longest character continuously

王林
王林forward
2024-02-11 15:24:101045browse

golang repeats the longest character continuously

php editor Baicao introduces you to an interesting problem-solving method - "golang continuously repeats the longest character". The core of this problem is to find the most consecutive characters and their number in a string. In Golang, we can achieve this function by looping through each character of the string and using counters and maximum variables. With this simple and efficient algorithm, we can easily solve this problem and get accurate results. Next, let us learn about the specific implementation process!

Question content

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
}

//// expected : {c: 0, l: 0} equal : {c: 98, l: 1}

I'm trying to complete https://www.codewars.com/kata/586d6cefbcc21eed7a001155/train/go The longest continuously repeated character For my tests it works fine But when I push to cw it fails to complete the bend test please help me Maybe I can improve my code somewhere or something I'm confused about

Solution

Your solution is too complicated. simplify.

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! :)

The above is the detailed content of golang repeats the longest character continuously. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete