【题解】Leetcode.318. Maximum Product of Word Lengths
2016-07-30 20:18
417 查看
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.
题目大意:
给出一个只由小写字母组成的字符串数组,找出 字符串i的长度 × 字符串j的长度 最大的值,并且字符串i与字符串j中没有共同的字符。
思路:
首先为每个字符串建立一个包含字符的2进制表并计算长度,然后枚举所有字符串对,如果这对字符串的2进制表没有重合,就计算长度积并更新最大积。
实现:
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.
题目大意:
给出一个只由小写字母组成的字符串数组,找出 字符串i的长度 × 字符串j的长度 最大的值,并且字符串i与字符串j中没有共同的字符。
思路:
首先为每个字符串建立一个包含字符的2进制表并计算长度,然后枚举所有字符串对,如果这对字符串的2进制表没有重合,就计算长度积并更新最大积。
实现:
int maxProduct(char** words, int wordsSize) { int *rec = (int*)malloc(sizeof(int)*wordsSize); // 2进制表 int *len = (int*)malloc(sizeof(int)*wordsSize); // 长度表 int rst = 0; char *p; for(int i = 0; i < wordsSize; i++){ rec[i] = 0; for(p=words[i];*p;rec[i] |= 1<<(*p++-'a')); // 将对应位置1 len[i] = p-words[i]; // 计算长度 } for(int i = 0;i<wordsSize;i++) for(int j = i+1;j<wordsSize;j++) if(!(rec[i]&rec[j])) // 如果没有重叠位 if(len[i] * len[j] > rst) rst = len[i] * len[j]; free(rec); free(len); return rst; }
相关文章推荐
- [PHP] constant variable
- 第八章 RMAN备份
- android 网络开发相关资料
- java-ee
- 简陋自写intList--双色球实例
- 2016_NENU_SoftWare_Summer_ Training_1
- LINUX的文件链接,管道和用户组
- Hdu 4588 Count The Carries (规律)
- 动态类型
- Anroid优化(二)_内存优化
- 2015-2016ACM-ICPC NEER northern-subregional-contest E Easy Arithmetic 思维、模拟
- Uva540 队列与map
- 关于 jsp 解析特殊字符的问题
- 新闻客户端功能类集合
- light oj贪心
- Linux -- bash
- 北斗得与失(1-二次编码的缺点)
- Smarty练习增删改
- Spring 注解@ResponseBody,@RequestBody,@PathVariable
- URLEncoder和URLDecoder实现转码和解码