栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Leetcode 318. 最大单词长度乘积

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Leetcode 318. 最大单词长度乘积

原题链接:Leetcode 318. 最大单词长度乘积

自己写的代码 哈希:

class Solution {
public:
    int maxProduct(vector& words) {
        int n=words.size();
        int res=0;
        vector> v(n,vector(26));
        for(int i=0;i
            for(int j=0;j
                int tmp=words[i][j]-'a';
                v[i][tmp]=1;
            }
        }
        for(int i=0;i
            for(int j=i+1;j
                int f=1;
                for(int k=0;k
                    int tmp=words[i][k]-'a';
                    if(v[j][tmp]==1) { f=0; break;}
                }
                if(f) 
                {
                    int len=words[i].size()*words[j].size();
                    res=max(res,len);
                }
            }
        }
        return res;
    }
};

位运算:

class Solution {
public:
    int maxProduct(vector& words) {
        int n=words.size(), res=0;
        vector v(n);
        for(int i=0;i
            for(int j=0;j
                int tmp=words[i][j]-'a';
                v[i]|=(1<
            for(int j=i+1;j
                if((v[i]&v[j])==0)//位运算要注意优先级,最好是打括号
                {
                    res=max(res,int(words[i].size()*words[j].size()));
                }
            }
        }
        return res;
    }
};

位运算优化:

class Solution {
public:
    int maxProduct(vector& words) {
        int n=words.size(), res=0;
        unordered_map mp;
        for(int i=0;i
            int num=0,len=words[i].size();
            for(int j=0;j
                int tmp=words[i][j]-'a';
                num|=(1<
            int num1=it1.first,len1=it1.second;
            for(auto it2:mp)
            {
                int num2=it2.first,len2=it2.second;
                if((num1&num2)==0)  res=max(res,len1*len2);
            }
        }
        return res;
    }
};

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/931810.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号