很显然2层for循环就可以搞定,但是时间复杂度O(n2),就不多赘述了。下面介绍2种效率更高的算法。
方法一:借助逻辑运算
用2个26位二进制标识2个字符串中26个字母的存在情况,然后进行与操作,结果非0,表示含有相同的字符。
注意:这种方法的限制是每个字符都是字母。原因是int是32位,即使换成64位的long,也仅仅能存放所有的大小写字母。
下面这个例子只写了字符串中只包含小写字母的情况:
String s1, s2;
int[] s = new int[2];
for(Char c : s1) {
s[0] = 1 << c - 'a';
}
for(Char c : s2) {
s[1] = 1 << c - 'a';
}
return s[0] & s[1];
方法二:数组
这里用每个字符c-'a'的值作为index(如果含有其他类型字符灵活处理),value存放字符串s1 s2中,该字符的出现情况,不仅可以知道有没有相同的字符,还可以知道该字符在每个字符串中出现的次数
public class CharCount {
int count1;
int count2;
}
CharCount[] count = new CharCount[26];
for(Char c : s1) {
CharCount charCount;
index = c - 'a';
if(count[index] == null) {
charCount = new CharCount();
count[index] = charCount;
}
count[index].count1++;
}
for(Char c : s2) {
CharCount charCount;
index = c - 'a';
if(count[index] == null) {
charCount = new CharCount();
count[index] = charCount;
}
count[index].count2++;
}
for(CharCount charCount : count) {
if(charCount.count1 != 0 && charCount.count2 != 0) {
return true
}
}
return false;