lintcode练习-133. Longest Word

204 篇文章 0 订阅
190 篇文章 5 订阅

133. Longest Word

给一个词典,找出其中所有最长的单词。

样例

在词典

{
  "dog",
  "google",
  "facebook",
  "internationalization",
  "blabla"
}

中, 最长的单词集合为 ["internationalization"]

在词典

{
  "like",
  "love",
  "hate",
  "yes"
}

中,最长的单词集合为 ["like", "love", "hate"]

挑战

遍历两次的办法很容易想到,如果只遍历一次你有没有什么好办法?

利用哈希表,可以做到只遍历一次

#利用hash表来存储
    def longestWords(self, dictionary):
        # write your code here
        hashmap = {}
        max_key = 0
        for item in dictionary:
            if max_key < len(item):
                max_key = len(item)
            if len(item) not in hashmap:
                hashmap[len(item)] = [item]
            else:
                hashmap[len(item)].append(item)
        
        return hashmap[max_key]

两行代码解决

 def longestWords(self, dictionary):
        # write your code here
        mlen = max(len(word) for word in dictionary)
        return [word for word in dictionary if len(word) == mlen]

 

function pdemodel [pde_fig,ax]=pdeinit; pdetool('appl_cb',5); set(ax,'DataAspectRatio',[1 1 1]); set(ax,'PlotBoxAspectRatio',[1.5 1 1]); set(ax,'XLim',[-1.5 1.5]); set(ax,'YLim',[-1 1]); set(ax,'XTick',[ -1.5,... -1.2,... -0.90000000000000002,... -0.60000000000000009,... -0.30000000000000004,... 0,... 0.30000000000000004,... 0.60000000000000009,... 0.90000000000000002,... 1.2,... 1.5,... ]); set(ax,'YTickMode','auto'); pdetool('gridon','on'); % Geometry description: pderect([-1 0.5 0.5 -0.5],'R1'); set(findobj(get(pde_fig,'Children'),'Tag','PDEEval'),'String','R1') % Boundary conditions: pdetool('changemode',0) pdesetbd(4,... 'dir',... 1,... '1',... '0') pdesetbd(3,... 'dir',... 1,... '1',... '0') pdesetbd(2,... 'dir',... 1,... '1',... '0') pdesetbd(1,... 'dir',... 1,... '1',... '200') % Mesh generation: setappdata(pde_fig,'Hgrad',1.3); setappdata(pde_fig,'refinemethod','regular'); setappdata(pde_fig,'jiggle',char('on','mean','')); setappdata(pde_fig,'MesherVersion','preR2013a'); pdetool('initmesh') % PDE coefficients: pdeseteq(1,... '1.0',... '0.0',... '0',... '1.0',... '0:10',... '0.0',... '0.0',... '[0 100]') setappdata(pde_fig,'currparam',... ['1.0';... '0 ']) % Solve parameters: setappdata(pde_fig,'solveparam',... char('0','1000','10','pdeadworst',... '0.5','longest','0','1E-4','','fixed','Inf')) % Plotflags and user data strings: setappdata(pde_fig,'plotflags',[2 1 1 1 1 1 1 1 0 0 0 1 1 1 1 0 0 1]); setappdata(pde_fig,'colstring',''); setappdata(pde_fig,'arrowstring',''); setappdata(pde_fig,'deformstring',''); setappdata(pde_fig,'heightstring',''); % Solve PDE: pdetool('solve')
07-23
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值