318MaximumProductofWordLengths

题意:输入字符串数组,输出找出最大的且不包含相同字符的两串字符串长度的乘积

思路:1、比较两个字符串str1、str2是否包含相同的字符

   >>> 将两个字符串排序,然后使用游标i,j判断str1[i]、str[j]大小,i++ / j++直至两个字符串结束/str[i]和str[j]相同,时间复杂度O(nlogn + mlogm + m + n)【超时】

   >>>将a-z 26个字符映射到4个字节(int)的从右向左数的各个位,通过&运算,如不为0则str1、str2存在相同字符,否则,则不同;时间复杂度O(m+n)

   2、乘积最大,暴力搜索法 O(数组长度^2)

       public int maxProduct(String[] words) {
    	int len = words.length;
    	//set up the map between word and int series
    	int[] map = new int[len];
    	char ch[];
    	int res = 0;
    	for(int i = 0; i < len; i++){
    		map[i] = 0;
    		ch = words[i].toCharArray();
    		for(int j = 0; j < ch.length; j++ ){
    			//premise : only lower case character contained
    			map[i] |= (1 << (ch[j] - 'a'));    			
    		}
    	}
    	//find the maximum of multiplication
    	for(int i = 0; i < len - 1; i++)
    		for(int j = i + 1; j < len; j++){
    			if((map[i] & map[j]) == 0 && res < words[i].length() * words[j].length())
    				res = words[i].length() * words[j].length();
    		}
    	return res;
    }


  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值