Golang code to check if first word can be formed from second word

huangapple go评论71阅读模式
英文:

Golang code to check if first word can be formed from second word

问题

我尝试了下面的 Golang 代码来检查第一个字符串是否可以由第二个字符串组成。这段代码有什么可以改进的地方吗?

package main
import (
	"fmt"
	"strings"
)

func main() {

	words := []string{"hello", "ellhoo"}

	result := "NO"

	s := words[0]
	for i := 0; i < len(words[0]); i++ {
		if strings.Contains(words[1], string(s[i])) == false {
			result = "NO"
			break
		} else {
			result = "YES"
			words[1] = strings.Replace(words[1],string(s[i]),"",1)
		}
	}
	fmt.Println(result)

}

这段代码的逻辑是检查第一个字符串 words[0] 中的每个字符是否都可以在第二个字符串 words[1] 中找到。如果找到了,就将第二个字符串中的该字符删除,继续检查下一个字符。如果找不到,则返回 "NO",否则返回 "YES"。

这段代码的实现是有效的,但是有一些可以改进的地方:

  1. 使用 strings.Contains 函数来检查字符是否存在于字符串中是一个比较耗时的操作,可以考虑使用 strings.Index 函数来获取字符在字符串中的索引,然后判断索引是否为 -1 来确定字符是否存在。

  2. 在每次找到字符后,使用 strings.Replace 函数来删除该字符,这也是一个比较耗时的操作。可以考虑使用切片操作来删除字符,以提高效率。

下面是改进后的代码:

package main
import (
	"fmt"
	"strings"
)

func main() {

	words := []string{"hello", "ellhoo"}

	result := "YES"

	s := words[0]
	for i := 0; i < len(words[0]); i++ {
		index := strings.Index(words[1], string(s[i]))
		if index == -1 {
			result = "NO"
			break
		} else {
			words[1] = words[1][:index] + words[1][index+1:]
		}
	}
	fmt.Println(result)

}

这样改进后的代码在查找字符和删除字符的过程中会更高效一些。

英文:

I tried below golang code to check if first string can be formed from second string. Is there any improvement that can be done on this code?

package main
import (
	&quot;fmt&quot;
	&quot;strings&quot;
)

func main() {

	words := []string{&quot;hello&quot;, &quot;ellhoo&quot;}

	result := &quot;NO&quot;

	s := words[0]
	for i := 0; i &lt; len(words[0]); i++ {
		if strings.Contains(words[1], string(s[i])) == false {
			result = &quot;NO&quot;
			break
		} else {
			result = &quot;YES&quot;
			words[1] = strings.Replace(words[1],string(s[i]),&quot;&quot;,1)
		}
	}
	fmt.Println(result)

}

答案1

得分: 3

记录源字符串中每个符文的计数,并将其存储在一个映射中。对于目标字符串中的每个符文,如果映射中的计数为零,则失败。递减计数。

以下是代码:

// canmake函数报告是否可以使用s中的符文构建t。
func canmake(t, s string) bool {
    m := map[rune]int{}
    for _, r := range s {
        m[r]++
    }
    for _, r := range t {
        if m[r] == 0 {
            return false
        }
        m[r]--
    }
    return true
}

以下是一个示例,展示如何使用它:

func main() {
    fmt.Println(canmake("hello", "ellhoo"))
    fmt.Println(canmake("hello", "elhoo")) // l的数量不足
    fmt.Println(canmake("hello", "elloo")) // 缺少h
}
英文:

Record the count of each rune in the source string in a map. For each rune in the target string, fail if count in map is zero. Decrement count.

Here's the code:

// canmake reports whether t can constructed from the runes in s.
func canmake(t, s string) bool {
	m := map[rune]int{}
	for _, r := range s {
		m[r]++
	}
	for _, r := range t {
		if m[r] == 0 {
			return false
		}
		m[r]--
	}
	return true
}

Here's an example showing how to use it:

func main() {
	fmt.Println(canmake(&quot;hello&quot;, &quot;ellhoo&quot;))
	fmt.Println(canmake(&quot;hello&quot;, &quot;elhoo&quot;)) // insufficent number of l
	fmt.Println(canmake(&quot;hello&quot;, &quot;elloo&quot;)) // mising h
}

huangapple
  • 本文由 发表于 2023年2月4日 08:02:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75342094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定