dongtiao1817
2019-02-22 05:50
采纳率: 100%
浏览 141
已采纳

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

Actually I am able to get it done using two loops in Go Language, for example if I have array as:

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

I need to return strings with maxLength. So output will be:

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

Here's what I am doing.

package main

import "fmt"

func allLongestStrings(inputArray []string) []string {
    maxLength := len(inputArray[0])
    outputArray := []string{}
    for _, value := range inputArray {
        if len(value) > maxLength {
            maxLength = len(value)
        }
    }
    for _, val := range inputArray {
        if len(val) == maxLength {
            outputArray = append(outputArray, val)
        }
    }
    return outputArray
}

func main() {
    xs := []string{"aa", "aab", "bcd", "a", "cdf", "bb"}
    fmt.Println(allLongestStrings(xs))
}

Is it possible to do this in one loop because I am running the same loop twice to find length and to append strings in outputArray.

Thanks In Advance.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题