HTMLify

LeetCode - Number of Valid Words in a Sentence - Go
Views: 30 | Author: abh
import "fmt"
func split_words(sentence string) []string {
	var words []string
	l, i := 0, 0
	for ; i<len(sentence); i++ {
		if sentence[i] == ' ' {
			words = append(words, sentence[l:i])
			l = i+1
		}
	}
	words = append(words, sentence[l:i])
	return words
}

func contain(c rune, s string) bool {
	for _, _c := range s {
		if c == _c {
			return true
		}
	}
	return false
}

func count(c rune, s string) int {
	var count_ int
	for _, _c := range s {
		if c == _c {
			count_++
		}
	}
	return count_
}

func countValidWords(sentence string) int {
	words := split_words(sentence)
	var count_ int
	for _, word := range words {
		valid := true
		if len(word) == 0 {
			continue
		}

		// digit check
		for _, d := range "0123456789" {
			if contain(d, word) {
				valid = false
				break
			}
		}

		// hypne check
		hc := count('-', word)
		if hc > 1 {
			continue
		} else if hc == 1 {
			if word[0] == '-' || word[len(word)-1] == '-' {
				continue
			}
		}

		// punctuation check
		var pc int
		for _, p := range ",.!" {
			pc += count(p, word)
		}

		if pc > 1 {
			continue
		} else if pc == 1 {
			var pp rune
			for _, p := range ",.!" {
				if contain(p, word) {
					pp = p
					break
				}
			}
			if word[len(word)-1] != byte(pp) {
				continue
			}
			if len(word) >= 2 {
				if word[len(word)-2] == '-' {
					continue
				}
			}
		}
		if valid {
			fmt.Println("|walid word>", word)
			count_++
		}
	}
	return count_
}

Comments