318.maximum-product-of-word-lengths.go 504 B

123456789101112131415161718192021222324252627
  1. type pair struct {
  2. _1 int
  3. _2 int
  4. }
  5. func maxProduct(words []string) (product int) {
  6. n := len(words)
  7. if n <= 1 {
  8. return
  9. }
  10. pairs := make([]pair, n)
  11. for i := 0; i < n; i++ {
  12. mask, l := 0, len(words[i])
  13. for j := 0; j < l; j++ {
  14. mask |= 1 << uint(words[i][j]-'a')
  15. }
  16. pairs[i] = pair{mask, l}
  17. }
  18. for i := 0; i < n-1; i++ {
  19. for j := i + 1; j < n; j++ {
  20. if pairs[i]._1&pairs[j]._1 == 0 && product < pairs[i]._2*pairs[j]._2 {
  21. product = pairs[i]._2 * pairs[j]._2
  22. }
  23. }
  24. }
  25. return
  26. }