371. Sum of Two Integers\318. Maximum Product of Word Lengths\208. Implement Trie\201.Bitwise AND
来源:互联网 发布:php获取不到post数据 编辑:程序博客网 时间:2024/06/04 18:13
- Sum of Two Integers
- DESCRIPTION
- IMPLEMENTATION
- Maximum Product of Word Lengths
- DESCRIPTION
- IMPLEMENTATION
- Implement Trie Prefix Tree
- DESCRIPTION
- IMPLEMENTATION
- Bitwise AND of Numbers Range
- DESCRIPTION
- IMPLEMENTATION
371. Sum of Two Integers
DESCRIPTION
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3.
使用bit manipulation做加法,不使用+-符号。
IMPLEMENTATION
这里我们需要知道最简单的加法器的操作。
bit a, b。
它们的和是 a ^ b, 进位是a && b。
如果加上进位,那么就是:
bit a,b, cf。
它们的和就是 a ^ b ^ c, 进位就是 (a && b || a && cf || b && cf)
So all in all, we can get the whole algorithm:
class Solution {public: int getSum(int a, int b) { int idx = 0, cf = 0, res = 0; while(idx < 32) { int get_a = a & (1 << idx); int get_b = b & (1 << idx); res |= (get_a ^ get_b ^ cf); cf = ((get_a && get_b) || (get_a && cf) || (get_b && cf)) ? 1 << (idx+1):0; idx++; } return res; }};
318. Maximum Product of Word Lengths
DESCRIPTION
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 16The two words can be "abcw", "xtfn".Example 2:Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]Return 4The two words can be "ab", "cd".Example 3:Given ["a", "aa", "aaa", "aaaa"]Return 0No such pair of words.
Calculate the multiply of two string’s length i witch both strings are contains different chars.
My algorithm is with low efficiency but AC.
1 construct the hash table for every string in the words.
2 go through every string str a in the vector
2.1 go through other strings str b in the vector
2.2 calculate length of these tweo strings len_mul.
2.3 update len_res if required
3 return result.
IMPLEMENTATION
My code shows below:
class Solution {public: vector<int> calculateHashForWord(string str) { vector<int> h(26, 0); for(int i = 0, size = str.length(); i < size; i++) h[str[i]-'a']++; return h; } bool isNotOverlapped(vector<int> a, vector<int> b) { int cnt = 0; while(cnt < 26) { if(a[cnt] && b[cnt]) return false; cnt++; } return true; } int maxProduct(vector<string>& words) { int num = words.size()? words.size():0; int res = 0; if(!num) return res; vector<vector<int>> hash(num, vector<int>(26, 0)); for(int idx = 0; idx < num; idx++) hash[idx] = calculateHashForWord(words[idx]); for(int idx_fst = 0; idx_fst < num - 1; idx_fst++) { int fst_len = words[idx_fst].length(); int sed = -1; for(int idx_sed = idx_fst; idx_sed < num; idx_sed++) { int sed_len = words[idx_sed].length(); if(sed < sed_len && isNotOverlapped(hash[idx_fst], hash[idx_sed]) && sed_len*fst_len > res) { res = sed_len*fst_len; sed = sed_len; } } } return res; }};
Also, there is some guy thinks about bit manipulation operation.
We just need one int to record the hash of one string(we use bit 1 to indicate there exists, 0 for ont exists)
Algorithm steps show below:
1 go through words with var words[i]
1.1 calculate hash with bit manipulation for words[i] to hash[i]
1.2 go through string which has lower index than i
1.3 update result if condition satisfied.
2 return result.
class Solution {public: int maxProduct(vector<string>& words) { int res = 0; int size = words.size(); if(!size) return res; vector<int> hash(size, 0); for(int idx = 0; idx < size; idx++) { int len_idx = words[idx].size(); for(auto ch:words[idx]) hash[idx] |= 1 << (ch - 'a'); for(int idx_sed = 0; idx_sed < idx; idx_sed++) if(!(hash[idx]&hash[idx_sed]) && len_idx*words[idx_sed].size() > res) res = len_idx*words[idx_sed].size(); } return res; }};
208. Implement Trie (Prefix Tree)
DESCRIPTION
Implement a trie with insert, search, and startsWith methods.
Fulfill the whole trie(prefix) tree with inser, search, search for prefix tree.
Here I use the data structure with 26 Node points to indicate 26 chars and one flag to indicate the termination of one word.
IMPLEMENTATION
The code shows below:
class Trie { Trie* next[26]; bool isTermination = false;public: /** Initialize your data structure here. */ Trie():isTermination(false) { memset(this->next, 0, 26*sizeof(Trie*)); } /** Inserts a word into the trie. */ void insert(string word) { Trie* cur = this; for(int idx = 0, size = word.length(); idx < size; idx++) { if(!cur->next[word[idx]-'a']) cur->next[word[idx]-'a'] = new Trie(); cur = cur->next[word[idx]-'a']; } cur->isTermination = true; } /** Returns if the word is in the trie. */ bool search(string word) { Trie* cur = this; for(int idx = 0, size = word.length(); idx < size; idx++) { if(!cur->next[word[idx]-'a']) return false; cur = cur->next[word[idx]-'a']; } return cur->isTermination; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { Trie* cur = this; for(int idx = 0, size = prefix.length(); idx < size; idx++) { if(!cur->next[prefix[idx]-'a']) return false; cur = cur->next[prefix[idx]-'a']; } return true; }};/** * Your Trie object will be instantiated and called as such: * Trie obj = new Trie(); * obj.insert(word); * bool param_2 = obj.search(word); * bool param_3 = obj.startsWith(prefix); */
Bitwise AND of Numbers Range
DESCRIPTION
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
For example, given the range [5, 7], you should return 4.
This problem is tricky. If you use iterative method, you will get TLE.
So we get deeper into this problem and we find that the AND between [m, n] is bit from the same head part of these two number. Like 4 and 7, (2’b100 and 2’b111) with the same head 2’b100, other part is different, so it’s zero.
IMPLEMENTATION
use mask to all 1s. Then shift the number to get the same part between m and n.
class Solution {public: int rangeBitwiseAnd(int m, int n) { if(m > n) return 0; int mask = ~0; while((mask&m) != (mask&n)) mask <<= 1; return mask & m; }};
- POJ2190 HDU2714 ISBN
- leetcode题解Java | 208. Implement Trie (Prefix Tree)
- 欢迎使用CSDN-markdown编辑器
- Intellij IDEA如何使用Maven Tomcat Plugin运行web项目
- [Vue2 + ElementUI]开发记录
- 371. Sum of Two Integers\318. Maximum Product of Word Lengths\208. Implement Trie\201.Bitwise AND
- mysql之外连接的用法
- 《Java高并发程序设计》学习 --7.8 Actor的内置转换状态
- win10常用技巧
- Python爬虫学习一——requests库
- Cannot invoke Tomcat manager 和Connection refused: connect
- 云服务器上Tomcat如何隐藏8080端口号
- require.js的使用
- 解决执行脚本报syntax error: unexpected end of file或syntax error near unexpected token `fi'错误的问题