Home  >  Article  >  Backend Development  >  Golang code to check if first word can be composed of second word

Golang code to check if first word can be composed of second word

WBOY
WBOYforward
2024-02-10 23:40:18814browse

Golang 代码检查第一个单词是否可以由第二个单词组成

In Golang, we often need to check whether a word can be composed of characters from another word. This function is useful in many situations, such as determining whether a string is a rearrangement of the letters of another string. In this article, PHP editor Xinyi will introduce you to a simple and efficient method to achieve this function. With this method, we can easily determine whether a word can be composed of characters from another word, thus improving the efficiency of our code. Let’s take a look at the specific implementation method!

Question content

I tried the following golang code to check if the first string can be composed of the second string. Is there anything that could be improved about this code?

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)

}

Workaround

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

code show as below:

// 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
}

The following examples show how to use it:

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

The above is the detailed content of Golang code to check if first word can be composed of second word. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete