• leetcode 318. Maximum Product of Word Lengths


    传送门

    318. Maximum Product of Word Lengths

       My Submissions
    Total Accepted: 19855 Total Submissions: 50022 Difficulty: Medium

    Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.

    Example 1:

    Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
    Return 16
    The two words can be "abcw", "xtfn".

    Example 2:

    Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
    Return 4
    The two words can be "ab", "cd".

    Example 3:

    Given ["a", "aa", "aaa", "aaaa"]
    Return 0
    No such pair of words.

    Credits:
    Special thanks to @dietpepsi for adding this problem and creating all test cases.

    Subscribe to see which companies asked this question

    Hide Tags
     Bit Manipulation
     
     
    题解:
     
     find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters.
    重点在于 判断 有没有重复的字母
    由于只有小写字母(26个),所以用 状压,位运算 (与)即可
     
     
     1 class Solution {
     2 public:
     3     int maxProduct(vector<string>& words) {
     4         int n = words.size();
     5         vector <int> len;
     6         vector <int> contain;
     7         int i,j;
     8         int l;
     9         for(i = 0;i < n;i++){
    10             l = words[i].length();
    11             len.push_back(l);
    12             int tmp = 0;
    13             for(j = 0;j < l;j++){
    14                 int x = words[i][j] - 'a';
    15                 tmp |= (1 << x);
    16             }
    17             contain.push_back(tmp);
    18         }
    19         int re = 0;
    20         for(i = 0;i < n;i++){
    21             for(j = i + 1;j < n;j++){
    22                 if(contain[i] & contain[j]){
    23                     continue;
    24                 }
    25                 re = max(re,len[i] * len[j]);
    26             }
    27         }
    28         return re;
    29     }
    30 };
  • 相关阅读:
    TokenType ([{}{}()])[{}]{}
    C# netcore 开发WebService(SoapCore)
    C++求快速幂
    二分法与牛顿迭代法求方程根
    Obtaining a Thorough CS Background Online (线上CS深度学习攻略)
    Elasticsearch 堆空间配置
    S家lic
    如何用calibredrv 来merge多个cell的gds
    siliconsmart feature
    openwrt的IPTV配置
  • 原文地址:https://www.cnblogs.com/njczy2010/p/5452724.html
Copyright © 2020-2023  润新知