LeetCode---Bit Manipulation && Design

**401. Binary Watch
思路:产生两个list分别代表小时和分钟,然后遍历

public List<String> readBinaryWatch(int num) {
    List<String> res = new ArrayList<String>();
    int[] hour = {8,4,2,1};
    int[] minute = {32,16,8,4,2,1};
    
    for(int i = 0; i <= num; i++){
        //i表示时和分各有几个灯亮,产生所有可能的值
        List<Integer> list1 = generateDigit(hour,i);
        List<Integer> list2 = generateDigit(minute,num - i);
        
        for(Integer num1 : list1){
            if(num1 >= 12) continue;
            for(Integer num2 : list2){
                if(num2 >= 60) continue;
                res.add(num1 + ":" + (num2 < 10 ? "0" + num2 : num2));
            }
        }
    }
    return res;
}

public List<Integer> generateDigit(int[] nums,int count){
    List<Integer> res = new ArrayList<Integer>();
    getResult(res,nums,count,0,0);
    return res;
}

public void getResult(List<Integer> res,int[] nums,int count,int start,int sum){
    if(count == 0){
        res.add(sum);
        return;
    }
    
    for(int i = start; i < nums.length; i++){
        getResult(res,nums,count - 1,i + 1,sum + nums[i]);
    }
}
**393. UTF-8 Validation
思路:判断每个UTF-8首Byte,看后面应该接几个Byte,再依次判断后面Byte的合法性,循环

public boolean validUtf8(int[] data) {
    if(data == null || data.length == 0) return false;
    for(int i = 0; i < data.length; i++){
        int numOfBytes = 0;
        if(data[i] > 255) return false;
        else if((data[i] & 128) == 0) {//0xxxxxxx
            numOfBytes = 1;
        }
        else if((data[i] & 224) == 192){//110xxxxx 
            numOfBytes = 2;
        }
        else if((data[i] & 240) == 224){//1110xxxx 
            numOfBytes = 3;
        }
        else if((data[i] & 248) == 240){//11110xxx 
            numOfBytes = 4;
        }
        else return false;
        
        for(int j = 1; j < numOfBytes; j++){
            if(i + j >= data.length) return false;
            if((data[i + j] & 192) != 128) return false;
        }
        //-1是因为上面的循环要+1
        i = i + numOfBytes - 1;
    }
    return true;
}
**211. Add and Search Word - Data structure design
思路:利用TrieTree,回溯
class TrieNode{
	TrieNode[] children = new TrieNode[26];
	String val = "";
}

public class WordDictionary {
TrieNode root = new TrieNode();

// Adds a word into the data structure.
public void addWord(String word) {
    TrieNode head = root;
    for(int i = 0; i < word.length(); i++){
        char c = word.charAt(i);
        if(head.children[c - 'a'] == null){
            head.children[c - 'a'] = new TrieNode();
        }
        head = head.children[c - 'a'];
    }
    head.val = word;
}

// Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
public boolean search(String word) {
    return match(word,0,root);
}

public boolean match(String word,int k,TrieNode root){
    if(k == word.length()) return !root.val.equals("");
    
    if(word.charAt(k) != '.'){
        int idx = word.charAt(k) - 'a';
        return root.children[idx] != null && match(word,k + 1,root.children[idx]);
    }
    else{
        for(int i = 0; i < 26; i++){
            if(root.children[i] != null && match(word,k + 1,root.children[i])) return true;
        }
        return false;
    }
}
}
总结
191. Number of 1 Bits:两种方法:1、每次和1作逻辑与,右移统计个数;2、n = n & (n - 1)每次消除一个1
342. Power of Four:两种方法:1、循环判断能不能被4整除,更新直到为1;2、大于0且是2的幂乘且排除是2的幂乘不是4的幂乘的数((num & 0x55555555) != 0)后者不需要循环求解
231. Power of Two:同上,1、循环判断能不能被2整除,更新直到为1;2、return n > 0 && (n & (n - 1)) == 0;或统计1的个数只有1个
371. Sum of Two Integers:return b == 0 ? a : getSum(a ^ b,(a & b) << 1);异或相当于不进位的加法,后面的左移相当于加上进位
461. Hamming Distance:依次比较每一位,不相同则加1
201. Bitwise AND of Numbers Range:m、n同时右移直到相等,然后当前m左移同样的位数
284. Peeking Iterator:利用优先队列,将元素添加进去以后直接求解
训练
**190. Reverse Bits:结果先左移,n再右移
**405. Convert a Number to Hexadecimal:类比二进制,每4位是一个字符,循环拼接后翻转
**338. Counting Bits:动态规划:res[i]表示数字i有几个1bit,res[i] = res[i >>> 1] + (i & 1)
**477. Total Hamming Distance:统计每一位上有几个1,几个0,乘积即为这一位上的距离
397. Integer Replacement:两种方法:1、若是偶数则除2,是奇数则取n - 1和n + 1中bit1少的那个,若是3只能取2;2、递归求解,注意考虑负数和越界。前者效率高
318. Maximum Product of Word Lengths:两种方法:1、利用抽屉法判断两个字符串是否有相同字符,依次更新最大值;2、构造数组存每个字符串对应的整型值,判断整型值作与运算是否为0,更新最大值,后者效率高很多
208. Implement Trie (Prefix Tree):利用字典树,下次训练尝试将类成员变成string
提示
1、统计bits中1的个数:n = n & (n - 1)
2、==的优先级高于逻辑运算
3、当出现一组数思考能不能通过全局观察得到解决方法
4、利用bit manipulation将字符串转化成整型判断有没有相同的字符:val[i] |= (1 << (words[i].charAt(j) - 'a'));
原文地址:https://www.cnblogs.com/LeonNew/p/6270128.html