zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    MyBatis 中#{}和${}区别
    MyBatis缓存机制
    SpringBoot整合RabbitMQ
    Jackson2JsonRedisSerializer和GenericJackson2JsonRedisSerializer的区别
    Docker安装MySql
    Python3网络爬虫(七):使用Beautiful Soup爬取小说
    python3 爬虫内涵段子
    python3 爬虫百度贴吧
    Python3网络爬虫(五):Python3安装Scrapy
    Requests: 模块
  • 原文地址:https://www.cnblogs.com/njczy2010/p/5452724.html
Copyright © 2011-2022 走看看