2019-02-01 Leetcode Day 4

1. Unique Morse Code Words

1.1 题目描述

给定一个字符串数组,利用摩斯密码表将字符串加密,找出经加密后,不同摩斯密码的个数
Example:
Input: words = ["gin", "zen", "gig", "msg"]
Output: 2
Explanation:
经过转换的摩斯密码有:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
有两种相异的摩斯密码,分别是:"--...--." 和 "--...-."

1.2 思路&解法

简单模拟:

class Solution(object):
    def uniqueMorseRepresentations(self, words):
        """
        :type words: List[str]
        :rtype: int
        """
        List = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        result = ""
        Set = set()
        for word in words:
            for c in word:
                index = ord(c) - ord('a')
                result = result + List[index]
            Set.add(result)
            result = ""
        return len(Set)

标准答案的实现代码如下:

class Solution(object):
    def uniqueMorseRepresentations(self, words):
        MORSE = [".-","-...","-.-.","-..",".","..-.","--.",
                 "....","..",".---","-.-",".-..","--","-.",
                 "---",".--.","--.-",".-.","...","-","..-",
                 "...-",".--","-..-","-.--","--.."]

        seen = {"".join(MORSE[ord(c) - ord('a')] for c in word)
                for word in words}

        return len(seen)

.join()方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
充分利用了python中迭代器的机制,但是两个答案思想都是一样的。

2. Max Increase to Keep City Skyline

2.1 问题描述

一个二位数组,数组的每一个元素都代表着一座楼房的高度。skyline代表着从四个方向看去,必须和原始的skyline一致。简单来说,我们用不同的角度去看这个二维矩阵,都有一个最大值的数组作为上限值。在保持这两个上限值数组不变的条件下,我们要将各个建筑的高度最大化,并且计算出各个建筑增加高度的和。
例如:
Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
Output: 35
Explanation:
The grid is:
[ [3, 0, 8, 4],
[2, 4, 5, 7],
[9, 2, 6, 3],
[0, 3, 1, 0] ]

The skyline viewed from top or bottom is: [9, 4, 8, 7]
The skyline viewed from left or right is: [8, 7, 9, 3]

The grid after increasing the height of buildings without affecting skylines is:

gridNew = [ [8, 4, 8, 7],
[7, 4, 7, 7],
[9, 4, 8, 7],
[3, 3, 3, 3] ]

2.2 思路与解答

初始思路:
初始思路是要先构造一个转置的矩阵,再构造两个skyline数组,最后根据两个skyline数组增加楼的高度。
经过优化后,两个skyline的数组可以同时进行计算。这里利用了zip函数巧妙地将矩阵进行了转置,并且利用enumerate构造了一个可迭代序列。

    def maxIncreaseKeepingSkyline(self, grid):
        row_maxes = [max(row) for row in grid]
        col_maxes = [max(col) for col in zip(*grid)]

        return sum(min(row_maxes[r], col_maxes[c]) - val
                   for r, row in enumerate(grid)
                   for c, val in enumerate(row))

你可能感兴趣的:(2019-02-01 Leetcode Day 4)