HTMLify
LeetCode - Number of Valid Words in a Sentence - Go
Views: 299 | Author: abh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | 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_ } |