Arrays 如何查找数组中最长的字符串?
实际上,我可以使用Go语言中的两个循环来完成它,例如,如果我的数组为:Arrays 如何查找数组中最长的字符串?,arrays,string,go,Arrays,String,Go,实际上,我可以使用Go语言中的两个循环来完成它,例如,如果我的数组为: ["aa", "aab", "bcd", "a", "cdf", "bb"] 我需要返回带有maxLength的字符串。因此,输出将是: ["aab", "bcd", "cdf"] 这就是我正在做的 package main import "fmt" func allLongestStrings(inputArray []string) []string { maxLength := len(inputArr
["aa", "aab", "bcd", "a", "cdf", "bb"]
我需要返回带有maxLength的字符串。因此,输出将是:
["aab", "bcd", "cdf"]
这就是我正在做的
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))
}
是否可以在一个循环中执行此操作,因为我正在两次运行同一个循环以查找长度并在outputArray中追加字符串
提前感谢。试试这个:
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 {
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]
}
func allLongestStrings(inputArray[]string)[]string{
n:=0
最大值:=-1
对于i,s:=范围输入阵列{
如果len(s)max{
//找到更长的字符串。请更新最大值并重置结果。
最大值=长度(s)
n=0
}
输入阵列[n],输入阵列[i]=输入阵列[i],输入阵列[n]
n++
}
返回输入阵列[:n]
}
我会使用排序包来完成。基本上,您要做的是通过实现和使用自定义排序函数来创建自定义排序函数
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)
}
主程序包
导入“排序”
输入“fmt”
类型sortByLength[]字符串
//Len实现sort.Interface的Len
func(s排序长度)Len()int{
返回透镜(s)
}
//Swap实现了sort.Interface的交换
func(s排序长度)交换(i,j int){
s[i],s[j]=s[j],s[i]
}
//Less实现了较少的sort.Interface
func(s排序长度)减去(i,j int)布尔{
返回len(s[i])>len(s[j])
}
func main(){
toFind:=[]字符串{“aa”、“aab”、“bcd”、“a”、“cdf”、“bb”}
//我们按长度降序排序
sort.sort(排序长度(toFind))
//第一个元素肯定是最长的
最长:=[]字符串{toFind[0]}
//如果我们在toFind中有多个元素。。。
如果len(toFind)>1{
//…我们需要找到toFind的所有剩余元素。。。
对于z,str:=范围toFind[1:]{
//…不小于最长长度的第一个元素。
如果len(str)
然而,虽然您自己的代码中只有一个循环,但排序显然也会对输入进行迭代。例如,更高效的
阅读,还有改进的余地。例如,对于最大值和最小值问题,避免使用特殊值作为初始最大值或最小值。不要过度分配内存,不要留下悬空的指针 Go
字符串
实现为:
type stringStruct struct {
str unsafe.Pointer
len int
}
如果列表由1000个长度为1000的字符串和一个长度为1001的字符串组成,则返回的列表的长度为1,容量至少为1000。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
}
主程序包
进口(
“fmt”
“字符串”
“不安全”
)
类型stringStruct struct{
str.Pointer
莱恩内特酒店
}
func main(){
var l[]字符串
对于n:=0;n<1000;n++{
l=追加(l,字符串。重复(“x”,1000))
}
l=l[:0]
l=追加(l,字符串。重复(“y”,1001))
over:=(cap(l)-len(l))*int(unsafe.Sizeof(stringStruct{}))
对于i,o:=len(l),l[:cap(l)];i
游乐场:
为了使程序正确,它必须是可读的。首先,编写基本算法,不要因为错误或特殊情况而分心
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[]字符串
对于uz,s:=范围a{
如果len(l[0])0{
l=追加(l,a[0])
a=a[1:]
}
对于uz,s:=范围a{
如果len(l[0])0{
l=追加(l,a[0])
a=a[1:]
}
对于uz,s:=范围a{
如果len(l[0])排序修改原始切片并在内部循环。在任何情况下,排序方法都可以使用已排序切片的前缀,而不是创建新的结果切片。所有有效点。我将相应地修改答案。但是,没有明确说明需要更改原始切片。
type stringStruct struct {
str unsafe.Pointer
len int
}
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
}
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)
}
}
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...)