Leetcode ☞ 318. Maximum Product of Word Lengths ☆
来源:互联网 发布:海马苹果助手for mac 编辑:程序博客网 时间:2024/06/11 01:18
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.
我的AC(40ms,击败76%):
int maxProduct(char** words, int wordsSize) { int* bitForm = (int*)calloc(wordsSize, sizeof(int)); int* lengths = (int*)calloc(wordsSize, sizeof(int)); int max = 0, ans; for(int i = 0; i < wordsSize; i++){ char* c = words[i]; while(*c){ bitForm[i] |= 1 << (*c++ - 'a'); lengths[i]++; }//算出第i个字符串的bit形式及其长度 for(int j = 0 ; j < i ; j++){ if ( (bitForm[i] & bitForm[j]) == 0){//(bitForm[i] & bitForm[j]) == 0 如果不加括号。就先运行==,再运行&。 ans = lengths[i] * lengths[j]; max = ans > max ? ans : max ; } } } free(bitForm); free(lengths); return max;}
分析:
1、把字符串转换成int型的01序列【只含有a~z这26个字母,26位是在int型范围内的】:在字母表中排第几,就在第几(低)位,如 “acd”==>“1101”。“或运算”,不论某字母出现几次,该位都会为1。
通过以上转换,判断两字符串是否含有相同字母 ==> 判断两个int型数的&结果是否不为0
2、该题依旧用到了这个小技巧(在前【时间顺序/AC更高】几题出现过多次):
char* c = words[i];
while(*c){巴拉巴拉的操作}
3、运算符优先级(“==”比“&”要高):
http://baike.baidu.com/link?url=l2dYzwoSVqEWM7YbolOqQmHAVTTJkk8D6gVjzcV9JoQtkh_6DynS1j4YIEmJXcDP_6VIyg7m4azVDjY35TOvWq
- Leetcode ☞ 318. Maximum Product of Word Lengths ☆
- 【leetcode】318. Maximum Product of Word Lengths
- 318. Maximum Product of Word Lengths LeetCode
- [leetcode] 318. Maximum Product of Word Lengths
- LeetCode: 318. Maximum Product of Word Lengths
- LeetCode 318. Maximum Product of Word Lengths
- leetcode 318. Maximum Product of Word Lengths
- [LeetCode]318. Maximum Product of Word Lengths
- [LeetCode]318. Maximum Product of Word Lengths
- LeetCode 318. Maximum Product of Word Lengths
- LeetCode *** 318. Maximum Product of Word Lengths
- [Leetcode] 318. Maximum Product of Word Lengths
- leetcode 318. Maximum Product of Word Lengths
- [leetcode]318. Maximum Product of Word Lengths
- 【LeetCode】318. Maximum Product of Word Lengths
- [LEETCODE]318. Maximum Product of Word Lengths
- 【leetcode】318. Maximum Product of Word Lengths
- [leetcode] 318. Maximum Product of Word Lengths
- Poj 2431 Expedition【stl】
- Charm Bracelet
- STM32F103程序串口调用printf打印数据
- POJ 2516 Minimum Cost(最小费用最大流)
- HDU 1286 找新朋友 (欧拉定理)
- Leetcode ☞ 318. Maximum Product of Word Lengths ☆
- 事件之信号量
- 异构计算
- win10怎么取消登录密码
- File文件
- 单向无头节点链表操作
- 安卓消息机制中的消息队列MessageQueue的插入轮询算法
- Android DiskLruCache 源码解析 硬盘缓存的绝佳方案
- CI框架 第三方接口QQ登录