谷歌算法面试题,数学的威力!
package com.iteye.bolide74.tester;public class Tester {public static void main(String[] args) {int[] prime = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103 };String strA = "ABCDEFGHIJKLMNO";String strB = "AFGHIJX";int strAlength = strA.length(), strBlength = strB.length();long strA2primes = 1, strB2primes = 1;for (int i = 0; i < strAlength; i++) {strA2primes *= prime[(strA.charAt(i) - 'A')];if (i < strBlength) {strB2primes *= prime[(strB.charAt(i) - 'A')];}}System.out.println(strA2primes % strB2primes == 0);}}
if (i < strBlength) {执行strAlength 次,执行strBlength次就ok了。
用bitmap的话是否更快些呢?
a="ABCDEFGHIJKLMNO"b="AFGHIJX"ra=0for c in a:ra+=2**(ord(c)-65)rb=0for c in b:rb+=2**(ord(c)-65)r = ra|rb==raprint ra="ABCDEFGHIJKLMNO" b="AFGHIJX" ra=0 for c in a: ra|=2**(ord(c)-65) rb=0 for c in b: rb|=2**(ord(c)-65) r = ra|rb==ra print r 10 楼 bolide74 2011-04-13 回各位同学的各种问题: