关键:怎么判断一致性?
解决:1.用最大长度为26的(因为最多有26种英文字母)“0、1”组成的序列统计字符串中拥有的字符(拥有则在对应位置置1)。
2.判断一致性:两个字符串对应的“0,1”序列,进行相与操作···
扫盲:
1.String.charAt(int index)
返回位于字符串的指定索引处的字符。(字符串的索引从零开始)
eg:String s = “hello world”;
char result = s.charAt(6);
//则result为w
2.Y |= (1<<X)
把1左移X位,并且和Y进行或运算。即,把Y的第X位置1。
3.两个字符相减,即它们的ASCLL码值相减。(ASCLL码值直接的差距)
eg: int x = ‘b’ - ‘a’;
//a对应ASCLL码值:97
//b对应ASCLL码值:98
//则x的值为1
class Solution {
public int countConsistentStrings(String allowed, String[] words) {
int ref = trans(allowed);
int total = 0; //用来统计“一致字符串”的个数
for (String word : words) {
int test = trans(word);
if((test & ref) == test){
total ++;
}
}
return total;
}
public int trans(String s) {
int ref = 0;
for(int i = 0; i < s.length(); i++) {
int x = s.charAt(i) - 'a';
ref |= (0 << x);
}
return ref;
}
}