zoukankan      html  css  js  c++  java
  • 318_Maximum Product of Word Lengths

    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".

    Example 2:

    Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
    Return 4
    The two words can be "ab", "cd".

    Example 3:

    Given ["a", "aa", "aaa", "aaaa"]
    Return 0
    No such pair of words.

    数组中每个元素是字符串

    首先,我们把每个字符串转换为一个int型数。该int型数有26位,哪个字母出现过,该位为1(!!重复的字母只算一次)

    其次,新得到的int型数组进行计算,两个int型数按位与(&)后为0则说明没有重复的字母

    最后,得到最大值

    public class Solution {
        public int MaxProduct(string[] words) {
            int[] intStore = new int[words.Length];
            int current = 0;
            int max = 0;
            
            for(int i = 0; i < words.Length; i++)
            {
                char[] ch = words[i].ToCharArray();
                current = 0;
                foreach(char c in ch.Distinct())
                {
                    int pow = (int)c - (int)'a';
                    current += (int)Math.Pow(2, pow);
                }
                intStore[i] = current;
            }
            
            for(int i = 0; i < intStore.Length; i++)
            {
                for(int j = i + 1; j < intStore.Length; j++)
                {  
                    if( (int)(intStore[i] & intStore[j]) == 0)
                    {
                        if(max < words[i].Length * words[j].Length) 
                        max = words[i].Length * words[j].Length;
                    }
                }
            }
            
            return max;
        }
    }
  • 相关阅读:
    javascript cookie
    mark几个比较好的配色网站
    Javascrip 淡入淡出思路
    实验报告:统计字符串中子字符串出现的次数
    Javascript计算器
    《node入门》学习
    配置ionic(低版本)
    eclipse环境配置
    关于文档加载的方法
    javascript基础-《web前端最佳实践》
  • 原文地址:https://www.cnblogs.com/Anthony-Wang/p/5124685.html
Copyright © 2011-2022 走看看