如何找到数组中最长的字符串?

时间:2019-02-22 05:50:50

标签: arrays string go

实际上,我可以使用Go语言中的两个循环来完成它,例如,如果我的数组为:

printf

我需要返回带有maxLength的字符串。因此输出将是:

["aa", "aab", "bcd", "a", "cdf", "bb"]

这就是我在做什么。

["aab", "bcd", "cdf"]

是否可以在一个循环中执行此操作,因为我在同一循环中运行了两次以查找长度并将字符串追加到outputArray中。

谢谢。

3 个答案:

答案 0 :(得分:5)

尝试一下:

func allLongestStrings(inputArray []string) []string {
    max := -1 // -1 is guaranteed to be less than length of string
    var result []string
    for _, s := range inputArray {
        if len(s) < max {
            // Skip shorter string
            continue
        }
        if len(s) > max {
            // Found longer string. Update max and reset result.
            max = len(s)
            result = result[:0]
        }
        // Add to result
        result = append(result, s)
    }
    return result
}

正如peterSO在另一个答案中指出的那样,结果切片的容量可能大于要求的容量,并且可以包含超过切片长度的字符串值。在某些情况下,额外的分配和字符串引用可能是一个问题(结果保留了很长时间,字符串很大,...)。如果分配和引用是一个问题,请返回copy of the slice

func allLongestStrings(inputArray []string) []string {
    ...
    return append([]string(nil), result...)
}

如果函数可以改变原始切片,则可以在输入切片中构造函数结果。这样可以避免分配结果切片。

func allLongestStrings(inputArray []string) []string {
    n := 0
    max := -1
    for i, s := range inputArray {
        if len(s) < max {
            // Skip shorter string
            continue
        }
        if len(s) > max {
            // Found longer string. Update max and reset result.
            max = len(s)
            n = 0
        }
        inputArray[n], inputArray[i] = inputArray[i], inputArray[n]
        n++
    }
    return inputArray[:n]
}

答案 1 :(得分:2)

我会通过使用sort包来做到这一点。基本上,您要做的是通过实现sort.Interface来创建自定义排序函数,并利用sort.Sort来发挥自己的优势。

package main

import "sort"
import "fmt"

type sortByLength []string

// Len implements Len of sort.Interface
func (s sortByLength) Len() int {
   return len(s)
}

// Swap implements Swap of sort.Interface
func (s sortByLength) Swap(i, j int) {
   s[i], s[j] = s[j], s[i]
}

// Less implements Less of sort.Interface
func (s sortByLength) Less(i, j int) bool {
    return len(s[i]) > len(s[j])
}

func main() {
    toFind := []string{"aa", "aab", "bcd", "a", "cdf", "bb"}

    // We sort it by length, descending
    sort.Sort(sortByLength(toFind))

    // The first element is sure to be the longest
    longest := []string{toFind[0]}

    // In case we have more than one element in toFind...
    if len(toFind) > 1 {

        // ...we need to find all remaining elements of toFind...
        for _, str := range toFind[1:] {

            // ...which are not smaller than the first element of longest.
            if len(str) < len(longest[0]) {

                // In case the current element is smaller in length, we can stop iterating
                // over toFind.
                break
            }

            // We know that str has the same length as longest[0], so we append it
            longest = append(longest, str)

        }
    }
    fmt.Println(longest)
}

Run it on Playground

但是,虽然您自己的代码中只有一个循环,但排序显然也会遍历输入。

答案 2 :(得分:1)

例如,@ThunderCat's solution的更有效版本,

package main

import "fmt"

func longest(a []string) []string {
    var l []string
    if len(a) > 0 {
        l = append(l, a[0])
        a = a[1:]
    }
    for _, s := range a {
        if len(l[0]) <= len(s) {
            if len(l[0]) < len(s) {
                l = l[:0]
            }
            l = append(l, s)
        }
    }
    return append([]string(nil), l...)
}

func main() {
    a := []string{"aa", "aab", "bcd", "a", "cdf", "bb"}
    fmt.Println(len(a), a)
    l := longest(a)
    fmt.Println(len(l), cap(l), l)
}

游乐场:https://play.golang.org/p/JTvl4wVvSEK

输出:

6 [aa aab bcd a cdf bb]
3 4 [aab bcd cdf]

阅读@ThunderCat's solution,还有改进的余地。例如,对于最大和最小问题,请避免使用特殊值作为初始最大值或最小值。不要整体分配内存,不要留下悬空的指针。

Go string的实现方式为:

type stringStruct struct {
    str unsafe.Pointer
    len int
}

如果列表包含1,000个长度为1000的字符串,然后是一个长度为1,001的字符串,则返回的列表的长度为1,容量至少为1,000。 999个条目具有指向1000个字节字符串的悬空指针,Go gc无法释放这些指针,浪费了超过1兆字节。

package main

import (
    "fmt"
    "strings"
    "unsafe"
)

type stringStruct struct {
    str unsafe.Pointer
    len int
}

func main() {
    var l []string
    for n := 0; n < 1000; n++ {
        l = append(l, strings.Repeat("x", 1000))
    }
    l = l[:0]
    l = append(l, strings.Repeat("y", 1001))

    over := (cap(l) - len(l)) * int(unsafe.Sizeof(stringStruct{}))
    for i, o := len(l), l[:cap(l)]; i < cap(l); i++ {
        over += len(o[i])
    }
    fmt.Println(over) // 1015368 bytes 64-bit, 1007184 bytes 32-bit 
}

游乐场:https://play.golang.org/p/Fi7EgbvdVkp


要使程序正确,必须可读。首先,编写基本算法,不要分散错误或特殊情况。

var l []string
for _, s := range a {
    if len(l[0]) <= len(s) {
        if len(l[0]) < len(s) {
            l = l[:0]
        }
        l = append(l, s)
    }
}

接下来,添加特殊情况,而不会破坏基本算法的流程。在这种情况下,请处理零长度和一长度列表。

var l []string
if len(a) > 0 {
    l = append(l, a[0])
    a = a[1:]
}
for _, s := range a {
    if len(l[0]) <= len(s) {
        if len(l[0]) < len(s) {
            l = l[:0]
        }
        l = append(l, s)
    }
}

最后,确保该功能对CPU和内存均有效。分配是精确的,没有指向未使用字符串的悬挂指针。

var l []string
if len(a) > 0 {
    l = append(l, a[0])
    a = a[1:]
}
for _, s := range a {
    if len(l[0]) <= len(s) {
        if len(l[0]) < len(s) {
            l = l[:0]
        }
        l = append(l, s)
    }
}
return append([]string(nil), l...)