位运算的应用。如果两个字符串包含相同的字符,那么其字符集的映射,一定在相同位置都为1,那么“与 ”运算后,必定结果不为0。
例如:
strA = "abcd"
strB = "bef"
codeA : 001111
codeB: 110010
codeA % code = 000010 = 2 != 0
class Solution {
/**
判断字符串有无公共字符(与运算),判断两个无序的、长度一致的字符串包含的字符完全相同(异或运算,结果为0相同)
*/
// 二进制位运算
public int maxProduct(String[] words) {
// 判空
if(words == null || words.length == 0){
return 0;
}
// 判断
int res = 0;
for(int i = 0;i < words.length;i++){
for(int j = i + 1; j < words.length; j++){
if(!hasCommonCharBinary(words[i],words[j])){
res = Math.max(res,words[i].length() * words[j].length());
}
}
}
return res;
}
// 二进制(用于都是大写或者都是小写的情况,用一个二进制数表示该字符串的字符集合)
public boolean hasCommonCharBinary(String a,String b){
int codeA = stringToInt(a);
int codeB = stringToInt(b);
// 如果没有相同的字符,对应位不会出现两个1,结果必然为0
if((codeA & codeB) != 0) {
return true;
}
return false;
}
// 字符串转二进制编码
public int stringToInt(String str) {
int res = 0;
// 对应第几位(0-25)
int offset = 0;
// 遍历字符串
for(int i = 0;i < str.length();i++) {
offset = str.charAt(i)- 'a';
// 将对应位置1
res |= (1 << offset);
}
return res;
}
}