How to check if a string can be constructed by using the letters of another string in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

func canConstruct(str, anotherStr string) bool {
    // ASCII frequency table
    var freq [256]int

    // Count characters in anotherStr
    for i := 0; i < len(anotherStr); i++ {
        freq[anotherStr[i]]++
    }

    // Check if str can be constructed
    for i := 0; i < len(str); i++ {
        ch := str[i]
        freq[ch]--
        if freq[ch] < 0 {
            return false
        }
    }

    return true
}

func main() {
    str := "hello"
    anotherStr := "olehhlxyz"

    fmt.Println(canConstruct(str, anotherStr))
}




/*
run:

true

*/

 



answered Jan 5 by avibootz

Related questions

...