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;
        }
    }
  • 相关阅读:
    基于密度的optics聚类算法
    unicode编码和utf-8编码详解
    聚类分析之k-prototype算法解析
    python学习笔记之正则表达式1
    聚类分析之模糊C均值算法核心思想
    Matlab编程笔记之GUI程序转exe
    Matlab学习笔记之安装教程
    SVPWM原理分析-基于STM32 MC SDK 5.0
    Allego Quick Reports
    SVPWM-实战
  • 原文地址:https://www.cnblogs.com/Anthony-Wang/p/5124685.html
Copyright © 2011-2022 走看看