显示标签为“Trie”的博文。显示所有博文
显示标签为“Trie”的博文。显示所有博文

2016年10月22日星期六

421. Maximum XOR of Two Numbers in an Array

Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231.
Find the maximum result of ai XOR aj, where 0 ≤ i, j < n.
Could you do this in O(n) runtime?
Example:
Input: [3, 10, 5, 25, 2, 8]

Output: 28

Explanation: The maximum result is 5 ^ 25 = 28.

题目希望找到两个数的XOR最大。
求数组中两两数字的异或运算的最大值,brute force的解法是O(n ^ 2),
怎么样才能XOR最大呢?我们从最大bit位上面看,如果有0,有1那么这位可以在答案中加上。

nums中,与mask按位与结果为0的所有数字,记为nums0

nums中,与mask按位与结果为1的所有数字,记为nums1
如果nums0与nums1其一为空,说明nums中所有数字在该二进制位同0或同1,其异或结果一定为0

如果nums0与nums1均不为空,说明nums中的数字在该位的异或值为1,令mask右移一位,再将nums0与nums1进一步划分成四部分:

nums0中,与mask按位与结果为0的所有数字,记为nums00

nums0中,与mask按位与结果为1的所有数字,记为nums01

nums1中,与mask按位与结果为0的所有数字,记为nums10

nums1中,与mask按位与结果为1的所有数字,记为nums11
分治法(Divide and Conquer)+ 位运算(Bit Manipulation)就是上面分析过程引用bookshadow的解法http://bookshadow.com/weblog/2016/10/15/leetcode-maximum-xor-of-two-numbers-in-an-array/

2.
一个比较直观的解法,用prefix Trie
对于每一个num来说,看它会不会构成最后的结果,就是看它的sibling有没有,如果有sibling,那么这位xor的结果就是1,不然xor的结果是0.对个num都做一遍,然后去取最大的值。https://discuss.leetcode.com/topic/63207/java-o-n-solution-using-trie/2


3. 构造这个xor结果

example: Given [14, 11, 7, 2], which in binary are [1110, 1011, 0111, 0010].
Since the MSB is 3, I'll start from i = 3 to make it simplify.
  1. i = 3, set = {1000, 0000}, max = 1000  
  2. i = 2, set = {1100, 1000, 0100, 0000}, max = 1100  -> 1110 0010 或者 1100 0010 或者 1010 0100 或者 1000 0110 都可以构成1110
  3. i = 1, set = {1110, 1010, 0110, 0011}, max = 1100
  4. i = 0, set = {1110, 1011, 0111, 0011}, max = 1101
外循环是31~0
因此每一位的比较,我们还需要知道前边那些位,比如我们这轮儿想要知道答案有没有111X(因为我们已经知道有11XX)因此我们取出每个数前3个bit位放入set。在set中利用想要知道的结果来找另一半。(x^y = z --> x^z = y   =》 x^y =  max(理想的) --> x^max = y))

int findMaximumXOR(vector<int>& nums) {
        int max = 0, mask = 0;
        unordered_set<int> t;
        // search from left to right, find out for each bit is there 
        // two numbers that has different value
        for (int i = 31; i >= 0; i--){
            // mask contains the bits considered so far
            mask |= (1 << i);
            t.clear();
            // store prefix of all number with right i bits discarded
            for (int n: nums){
                t.insert(mask & n);
            }
            
            // now find out if there are two prefix with different i-th bit
            // if there is, the new max should be current max with one 1 bit at i-th position, which is candidate
            // and the two prefix, say A and B, satisfies:
            // A ^ B = candidate
            // so we also have A ^ candidate = B or B ^ candidate = A
            // thus we can use this method to find out if such A and B exists in the set 
            int candidate = max | (1<<i);
            for (int prefix : t){
                if (t.find(prefix ^ candidate) != t.end()){
                    max = candidate;
                    break;
                }
                
            }
        }
        return max;
    }
https://discuss.leetcode.com/topic/63213/java-o-n-solution-using-bit-manipulation-and-hashmap/7



425. Word Squares

Given a set of words (without duplicates), find all word squares you can build from them.
A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns).
For example, the word sequence ["ball","area","lead","lady"] forms a word square because each word reads the same both horizontally and vertically.
b a l l
a r e a
l e a d
l a d y
Note:
  1. There are at least 1 and at most 1000 words.
  2. All words will have the exact same length.
  3. Word length is at least 1 and at most 5.
  4. Each word contains only lowercase English alphabet a-z.
Example 1:
Input:
["area","lead","wall","lady","ball"]

Output:
[
  [ "wall",
    "area",
    "lead",
    "lady"
  ],
  [ "ball",
    "area",
    "lead",
    "lady"
  ]
]

Explanation:
The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters).
Example 2:
Input:
["abat","baba","atan","atal"]

Output:
[
  [ "baba",
    "abat",
    "baba",
    "atan"
  ],
  [ "baba",
    "abat",
    "baba",
    "atal"
  ]
]

Explanation:
The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters).
参考
https://discuss.leetcode.com/topic/63516/explained-my-java-solution-using-trie-126ms-16-16


需要构造这个square,可以用backtracking。构造答案的时候check constraints

思路是典型思路,但是具体操作有所不同。

首先每一行的word可以重复,因此每次dfs的时候都是从所有words 中寻找合适的word

因此问题变成如何找合适的word

合适word:each word reads the same both horizontally and vertically.
当我们随便取n个word构成word square的时候,要看第i行是否与第i列相等。但是这样做cost 太大。
如果我们能够backtracking做就可以跳过不符合的word squares。因此我们需要转换“第i行是否与第i列相等”这个条件。
b a l l
a r e a
l e a d
l a d y
我们在看例子的时候可以发现只要按照图上构造就行。按照列的prefix来找行的word。
第二行的word就是满足prefix=='a'的那些word,第三行的word就是按照第二行取的结果满足prefix == 'le'(第三列的prefix)的那些wrod,第四行就是取以第四列prefix'lad'开头的words。如果没有答案就roll back 说明上面的构造不对。

因此在构造trie的时候,要在每个点存prefix是这个path的wordList

  class TrieNode{  
     TrieNode[] children;  
     List<String> wordList;  
     public TrieNode(){  
       children = new TrieNode[26];  
       wordList = new ArrayList<>();  
     }  
     public List<String> findWords(String prefix){  
       List<String> ans = new ArrayList<>();  
       List<TrieNode> candidates = new ArrayList<>();  
       candidates.add(root);  
       int n = prefix.length();  
       for(int i = 0; i < n; i++){  
         int t = prefix.charAt(i) - 'a';  
         int size = candidates.size();  
         for(int j = 0; j < size; j++){  
           TrieNode node = candidates.remove(0);  
           if(node.children[t]!=null){  
             candidates.add(node.children[t]);  
           }  
         }  
       }  
       for(TrieNode node: candidates){  
         ans.addAll(node.wordList);  
       }  
       return ans;  
     }  
   }  
   List<List<String>> ans = new ArrayList<>();  
   TrieNode root = null;  
   public List<List<String>> wordSquares(String[] words) {  
     root = buildTrie(words);  
     List<String> list = new ArrayList<>();
     //give every word a chance to be on top    
     for(String w: words){  
       list.add(w);  
       dfs(list,1,words[0].length());  
       list.remove(list.size()-1);  
     }  
     return ans;  
   }  
   public void dfs(List<String> list, int idx, int n){  
     if(idx == n){  
       ans.add(new ArrayList<>(list));  
       return;  
     }  
     //construct the prefix that needed to find next line word 
     //use trie to find words that start with those constraints, and dfs for each one of them  
     String prefix = "";  
     for(String s: list){  
       prefix+=s.charAt(idx);  
     }  
     List<String> words = root.findWords(prefix);  
     for(String word: words){  
       list.add(word);  
       dfs(list,idx+1,n);  
       list.remove(list.size()-1);  
     }  
   }  
   public TrieNode buildTrie(String[] words){  
     TrieNode root = new TrieNode();  
     for(int i = 0 ; i < words.length; i++){  
       String w = words[i];  
       TrieNode cur = root;  
       for(int j = 0; j < w.length(); j++){  
         int idx = w.charAt(j) - 'a';  
         if(cur.children[idx] == null){  
           cur.children[idx] = new TrieNode();  
         }  
         cur = cur.children[idx];  
         cur.wordList.add(words[i]);  
       }  
     }  
     return root;  
   }  

2016年10月7日星期五

Prefix that appears at least k times

given an array of strings and int k, find the prefix that appears at least k times.


 public class Solution {  
   class TrieNode{  
     TrieNode[] children;  
     int count;  
     boolean isEnd;  
     public TrieNode(){  
       count = 0;  
       children = new TrieNode[256];  
     }  
   }  
   public String kCommonPrefix(String[] strs, int k) {  
     TrieNode root = new TrieNode();  
     Stack<Character> path = new Stack<>();  
     int max = k;  
     for(int j = 0; j < strs.length; j++){  
       String s = strs[j];  
        TrieNode cur = root;  
        Stack<Character> tmp = new Stack<>();  
        for(int i = 0; i < s.length(); i++){  
          int x = s.charAt(i);  
          if(cur.children[x] == null){  
            cur.children[x] = new TrieNode();  
          }  
          cur.children[x].count++;  
          cur = cur.children[x];  
          if(cur.count >= max){  
            tmp.push(s.charAt(i));  
            max = cur.count;  
          }  
        }  
        if(tmp.size() > path.size()){  
          path = new Stack<>();  
          while(!tmp.empty()) path.push(tmp.pop());  
        }  
     }  
     StringBuilder sb = new StringBuilder();  
     while(!path.empty()){  
       sb.append(path.pop());  
     }  
     return sb.toString();  
   }  
 }