Saturday, 30 March 2019

Bit Manipulation Problems (5)

Let's look at another medium level problem and solve it with bitwise manipulation

Q318  Maximum Product of Word Lengths



 Use bit operations to mark
 a num:    1        binary:    00000001
 b num:    2        binary:    00000010
 c num:    4        binary:    00000100

 Then we can use | OR operator mark a string contains a, b, c as binary 00000111
 And we can compare if two strings have commom character by checking stringA & stringB != 0
 e.g.
 stringA  "abc" 00000111
 stringB  "ade" 00011001
 stringC  "def" 00111000

 stringA & stringB == 0  -> false
 stringC & stringB == 0  -> true

 We only need 16 bits, so UInt32 is enough for the solution

https://github.com/Sylvia-YiyinShen/Algorithm/blob/master/BitManipulation/Q318MaximumProduct.playground/Contents.swift




Other bit manipulation problems in my blog:
http://hadesmercury.blogspot.com/2019/03/bit-manipulation-problems-1.html
http://hadesmercury.blogspot.com/2019/03/bit-manipulation-problems-2.html
http://hadesmercury.blogspot.com/2019/03/bit-manipulation-problems-3.html
http://hadesmercury.blogspot.com/2019/03/bit-manipulation-problems-4.html

More bit manipulation problems at Leetcode:
https://leetcode.com/tag/bit-manipulation/

No comments:

Post a Comment