Leetcode 748. Shortest Completing Word

291 篇文章 2 订阅
146 篇文章 0 订阅

Problem

Given a string licensePlate and an array of strings words, find the shortest completing word in words.

A completing word is a word that contains all the letters in licensePlate. Ignore numbers and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more than once in licensePlate, then it must appear in the word the same number of times or more.

For example, if licensePlate = “aBc 12c”, then it contains letters ‘a’, ‘b’ (ignoring case), and ‘c’ twice. Possible completing words are “abccdef”, “caaacab”, and “cbca”.

Return the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words.

Algorithm

Count the list and the number of occurrences of each letter in each word and compare them.

Code

class Solution:
    def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
        dict_cnts = [0] * 26
        for c in licensePlate:
            if c >= 'a' and c <= 'z':
                index = ord(c) - ord('a')
                dict_cnts[index] = dict_cnts[index] + 1
            elif c >= 'A' and c <= 'Z':
                index = ord(c) - ord('A')
                dict_cnts[index] = dict_cnts[index] + 1
        
        min_len = 20
        min_id = -1
        slen = len(words)
        for i in range(slen):
            word_cnts = [0] * 26
            wlen = len(words[i])
            for c in words[i]:
                if c >= 'a' and c <= 'z':
                    index = ord(c) - ord('a')
                    word_cnts[index] = word_cnts[index] + 1
                elif c >= 'A' and c <= 'Z':
                    index = ord(c) - ord('A')
                    word_cnts[index] = word_cnts[index] + 1
            find = 1
            for j in range(26):
                if dict_cnts[j] > word_cnts[j]:
                    find = 0
                    break
            if find and min_len > wlen:
                min_len = wlen
                min_id = i
        if min_id >= 0:
            return words[min_id]
        else:
            return ""   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值