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

WBOY
Release: 2024-02-10 23:40:18
forward
886 people have browsed it

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)

}
Copy after login

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
}
Copy after login

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
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template