318. 最大单词长度乘积
1、暴力求解
1 class Solution 2 { 3 public: 4 int maxProduct(vector<string>& words) 5 { 6 int n = words.size(); 7 int res = 0; 8 for(auto& a : words) sort(a.begin(),a.end()); //每个单词按照字典序排列 9 for(int i = 0;i < n - 1;i ++) 10 { 11 for(int j = i + 1;j < n;j ++) 12 { 13 int a = 0,b = 0; 14 while(a < words[i].size() && b < words[j].size()) 15 { 16 if(words[i][a] < words[j][b]) a ++; 17 else if(words[i][a] > words[j][b]) b ++; 18 else break; 19 } 20 if(a == words[i].size() || b == words[j].size()) 21 { 22 res = max(res,(int)words[i].size() * (int)words[j].size()); 23 } 24 } 25 } 26 return res; 27 } 28 };
2、使用位运算
1 // a 00001 2 //ab 00011 3 //abc 00111 4 //d 01000 5 //cd 01100 6 //bcd 01110 7 //abcd 01111 8 9 //ab 00011 10 //cd 01100 11 // & ________ 12 // 00000 13 class Solution 14 { 15 public: 16 int maxProduct(vector<string>& words) 17 { 18 int n = words.size(); 19 vector<int> hash(n); 20 int res = 0; 21 for(int i = 0; i < n; ++i) 22 { 23 for(char c : words[i]) hash[i] |= 1 << (c-'a');//最关键的一步 24 } 25 for(auto a : hash) cout << a << endl; 26 27 for(int i = 0; i < n-1; ++i) 28 { 29 for(int j = i+1; j < n; ++j) 30 { 31 if((hash[i] & hash[j]) == 0) 32 res = max((int)words[i].size() * (int)words[j].size(),res); 33 } 34 } 35 return res; 36 } 37 };
Mamba never out

浙公网安备 33010602011771号