LeetCode318:Maximum Product Of Word Length

好久没刷LeetCode,昨天随便pick了一道。

    题目:

 

Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.

	Example 1:
	Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
	Return 16
	The two words can be "abcw", "xtfn".
首先看下题目要求,给定一个字符串数组,数组包含了随机的一些字符串,每个字符串包含n个字符,每个字符串所含的字符数两两相乘,求出相乘后的最大数,前提条件是两两相乘的两个字符串不含有相同的的字符,例如题目中的例子,abcdef含有六个字符,里应该返回24,但abcdef中含有与其他字符串中相同的字符,所以该字符串不能参与运算。

再说一下我的解题思路,首先每个字符串亮亮进行比较,所有字符串都比较完需要两层for循环,然后在每次两个比较的时候,需要比较字符串1中的字符是否在字符串2中出现,这就又需要一层循环,所以共需要三层循环。在最里层循环,即两个字符串比较时,假如字符串1中含有n个字符,如果n次循环后,字符串1中的字符都没在字符串2中出现,那就将两个字符串的字符数相乘,如果得到的值resut大于上一次的结果result,则将值赋值给结果result,依次下去。

public static int maxProduct(String[] words) {
        int result=0;
        int resut=0;
		for(int i=0;i<words.length-1;i++){
        	for(int j=i+1;j<words.length;j++){
        		for(int k=0;k<words[i].length();k++){
        			
        			int charge=words[j].indexOf(words[i].charAt(k));
        			if(charge>=0){
        				break;
        			}else{
        				if(k==(words[i].length()-1)){
        					resut=words[i].length()*words[j].length();
        					if(resut>result){
        						result=resut;
        					}
        				}
        			}
        		
        		}
        		
        	}
        }
		return result;
    }



猜你喜欢

转载自blog.csdn.net/wetsion/article/details/51004007