论坛首页 综合技术论坛

给大家出道题,算法的

浏览 32191 次
精华帖 (0) :: 良好帖 (1) :: 新手帖 (0) :: 隐藏帖 (17)
作者 正文
   发表时间:2012-02-01  
Write a function that takes as input list of words and prints out groups of words with exactly the same letters, one group per line.

For example,

Given the list:
hat, top, potter, pot, pier, ripe

It would print:
hat
top, pot
potter,
pier, ripe

Since ‘pier’ and ‘ripe’ each have one p, i, e, and r they belong on the same line. Since no other word has the same 6 letters as ‘potter’ it belongs on a line by itself.

Note: The order of the lines does not matter. As long as all words that belong on the same line are grouped together the function is correct.

Please use the following function signature:

void PrintGroupsWithSameLetters(string[] words)
   发表时间:2012-02-01  
这是某公司面试的homework吗?
0 请登录后投票
   发表时间:2012-02-01  
这样可不可以
先做遍历,
把每个单词按字母排序,排序完成的当作key 放到map中,value为一个就是没排序的值,
然后每次向map里加之前,get一下,发现不是null的,就在value后面继续添加。

最后把这个map的每个value打出来
0 请登录后投票
   发表时间:2012-02-01  
no1dog 写道
这样可不可以
先做遍历,
把每个单词按字母排序,排序完成的当作key 放到map中,value为一个就是没排序的值,
然后每次向map里加之前,get一下,发现不是null的,就在value后面继续添加。

最后把这个map的每个value打出来

你这个不太对吧。你把每个值按照字母顺序排列了出来,但要求是每行打印得是拥有相同字母的字符。
0 请登录后投票
   发表时间:2012-02-02  
jimwallet 写道
no1dog 写道
这样可不可以
先做遍历,
把每个单词按字母排序,排序完成的当作key 放到map中,value为一个就是没排序的值,
然后每次向map里加之前,get一下,发现不是null的,就在value后面继续添加。

最后把这个map的每个value打出来

你这个不太对吧。你把每个值按照字母顺序排列了出来,但要求是每行打印得是拥有相同字母的字符。

排序好的做为key,value是没排序的单词
0 请登录后投票
   发表时间:2012-02-02  
def PrintGroupsWithSameLetters(words):
    group = {} 
    for word in words:
        group.setdefault(''.join(sorted(word)), []).append(word)
    for wordgroup in group.values():
        print(wordgroup)

PrintGroupsWithSameLetters(['hat', 'top', 'potter', 'pot', 'pier', 'ripe' ])
0 请登录后投票
   发表时间:2012-02-02  
每个字母对应一个素数,
然后把所有单词响应的素数相乘,然后把结果做比较,结果相同的,说明这个单词和另一个单词又相同的字母
1 请登录后投票
   发表时间:2012-02-02  
现根据字符串长度进行分组, 然后再对字符串进行排序。  大体为第一步:归类(长度相等的一类) 第二步:给每个分组中的字符串排序再归类。 呵呵,有点mapreduce的意思哦。
1 请登录后投票
   发表时间:2012-02-02  
这个排序是容易的吧,如果是从简单的说,我拿java的来看吧,
首先建立以个map   最后是linkedmap<String, linkedList<String>>
然后和2L说的一样,key使用排序过的每个字母做key,(当然,在这你可以写一个相似度的工具算法
前些天我在论坛上看到的那个算法。这里简单的话,就排序吧。equal,就加入到linkedList里面去吧)
然后遍历map,,遍历map下的linkedList,然后换行 你会发现其实很简单,

但是从难点的说.比如说某某楼说的,首先按照长度分队列,(首先减少了算法的复杂度。),然后再按素数之积做相似度算法,怎么说呢,那就是说把工具丢一边,自己写和这个题目,更加相近的算法,为了兴趣可以去试下啊

但是为了面试,我不得不说,那点点可贵的时间就为了你闭门造车么- -

有点滑稽啊! - -
0 请登录后投票
   发表时间:2012-02-02  
hubeen 写道
def PrintGroupsWithSameLetters(words):
    group = {} 
    for word in words:
        group.setdefault(''.join(sorted(word)), []).append(word)
    for wordgroup in group.values():
        print(wordgroup)

PrintGroupsWithSameLetters(['hat', 'top', 'potter', 'pot', 'pier', 'ripe' ])

真好玩呢- -
原来我可能看着不知道说什么,最近看了perl,我发现   真是- -  一看就明白怎么回事啊,

话说python和perl的通用型,那个比较好呢
0 请登录后投票
论坛首页 综合技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics