Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,406 questions

56,397 answers

573 users

How to check whether the letters of a word exist in a string (order doesn't matter) in Go

1 Answer

0 votes
package main

import (
	"fmt"
	"unicode"
)

/*
ContainsWordLetters reports whether all letters in word can be
formed from the letters available in sentence.

Rules:
  - Letter order does not matter.
  - Comparison is case-insensitive.
  - Non-letter characters are ignored.
*/
func ContainsWordLetters(sentence, word string) bool {
	var available [26]int

	// Count available letters in the sentence.
	for _, r := range sentence {
		r = unicode.ToLower(r)

		if r >= 'a' && r <= 'z' {
			available[r-'a']++
		}
	}

	// Consume letters required by the word.
	for _, r := range word {
		r = unicode.ToLower(r)

		if r < 'a' || r > 'z' {
			continue
		}

		index := r - 'a'
		available[index]--

		if available[index] < 0 {
			return false
		}
	}

	return true
}

func main() {
	sentence := "Bright stars shine above calm valleys at night."

	fmt.Println(ContainsWordLetters(sentence, "satellite"))    // true
	fmt.Println(ContainsWordLetters(sentence, "satellllite"))  // false
}



/*
run:

true
false

*/

 



answered Sep 27 by avibootz

Related questions

...