zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 318 最大单词长度乘积

    318. 最大单词长度乘积

    给定一个字符串数组 words,找到 length(word[i]) * length(word[j]) 的最大值,并且这两个单词不含有公共字母。你可以认为每个单词只包含小写字母。如果不存在这样的两个单词,返回 0。

    示例 1:

    输入: [“abcw”,“baz”,“foo”,“bar”,“xtfn”,“abcdef”]
    输出: 16
    解释: 这两个单词为 “abcw”, “xtfn”。
    示例 2:

    输入: [“a”,“ab”,“abc”,“d”,“cd”,“bcd”,“abcd”]
    输出: 4
    解释: 这两个单词为 “ab”, “cd”。
    示例 3:

    输入: [“a”,“aa”,“aaa”,“aaaa”]
    输出: 0
    解释: 不存在这样的两个单词。

    PS:
    全是小写字母, 可以用一个32为整数表示一个word中出现的字母,
    hash[i]存放第i个单词出现过的字母, a对应32位整数的最后一位,
    b对应整数的倒数第二位, 依次类推. 时间复杂度O(N^2)
    判断两两单词按位与的结果, 如果结果为0且长度积大于最大积则更新

    class Solution {
       public int maxProduct(String[] words) {
            int n = words.length;
            int[] wordsBit = new int[n];
            for (int i = 0; i < n; i++) {
                wordsBit[i] = convertWordToBit(words[i]);
            }
            int max = 0;
            for (int i = 0; i < n; i++) {
                for (int j = i + 1; j < n; j++) {
                    if ((wordsBit[i] & wordsBit[j]) == 0) {
                        int newLength = words[i].length() * words[j].length();
                        max = max < newLength ? newLength : max;
                    }
                }
            }
            return max;
        }
    
        private int convertWordToBit(String word) {
            int wordBit = 0;
            int n = word.length();
            for (int i = 0; i < n; i++) {
                wordBit = wordBit | (1 << (word.charAt(i) - 'a'));
            }
            return wordBit;
        }
    }
    
  • 相关阅读:
    Deep Learning入门
    基本技能(一)
    NNCRF之NNSegmentation, NNPostagging, NNNameEntity
    word2vector 使用方法 计算语义相似度
    Berkeley parser使用方法
    zpar使用方法之Chinese Word Segmentation
    【delphi】delphi出现‘尚未调用CoInitialize’异常
    VS05 VS08 VS10 工程之间的转换
    odbc数据源for mysql
    【delphi】Delphi过程、函数传递参数的八种方式
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13075233.html
Copyright © 2011-2022 走看看