亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何找到數組中最長的字符串?

如何找到數組中最長的字符串?

Go
手掌心 2023-06-12 09:58:58
實際上,我可以使用 Go 語言中的兩個循環來完成它,例如,如果我有如下數組:["aa", "aab", "bcd", "a", "cdf", "bb"]我需要返回具有 maxLength 的字符串。所以輸出將是:["aab", "bcd", "cdf"]這就是我在做什么。package mainimport "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))}是否可以在一個循環中執行此操作,因為我正在運行相同的循環兩次以查找長度并在 outputArray 中附加字符串。
查看完整描述

3 回答

?
12345678_0001

TA貢獻1802條經驗 獲得超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

}

結果切片的容量可以大于所需的容量,并且可以包含超過切片長度的字符串值。額外的分配和字符串引用在某些情況下可能是個問題(結果保留很長時間,字符串很大,...)。如果分配和引用是一個問題,則返回切片的副本。


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]

}


查看完整回答
反對 回復 2023-06-12
?
jeck貓

TA貢獻1909條經驗 獲得超7個贊

我會通過使用 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)

}

然而,雖然您自己的代碼中只有一個循環,但排序顯然也會遍歷輸入。


查看完整回答
反對 回復 2023-06-12
?
MMMHUHU

TA貢獻1834條經驗 獲得超8個贊

例如

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]

例如,對于最大值和最小值問題,避免使用特殊值作為初始最大值或最小值。不要過度分配內存,也不要留下懸空指針。

Gostring實現為:

type stringStruct struct {

? ? str unsafe.Pointer

? ? len int

}

如果列表由 1,000 個長度為 1,000 的字符串和一個長度為 1,001 的字符串組成,則返回的列表的長度為 1,容量至少為 1,000。999 個條目有指向 1,000 字節字符串的懸垂指針,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...)


查看完整回答
反對 回復 2023-06-12
  • 3 回答
  • 0 關注
  • 228 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號