搜狐-笔试题


前几天,在清华一教参加了参加了搜狐的笔试,

题目大意

给定一个字符序列和一个字典,字典里的每个单词都在字符序列中.

你可以在字符序列中任意位置添加空格,使之构成句子.

输出所有的句子.


比如:

字符序列 characters="catsanddog"
字典dictionary=["cats","and","sand","dog","cat"]

输出:

cats and dog
cat sand dog


思路

回溯


代码

#hadoop@dream:~/sohu$ cat last.py
#!/usr/bin/env python

class Solution:
  dictionary=list()
  result=list()

  def __int__(self):
      pass

  def __int__(self,dictionary):
      self.dictionary=dictionary

  def newDictionary(self,dictionary):
    self.dictionary=dictionary
    self.result=list()

  def show(self):
    if self.result:
      print ' '.join(self.result)
    else:
      print "none"

  def solve(self,characters):
    characterslength=len(characters)
    if characterslength==0:
      self.show()
    for word in self.dictionary:
      if characters.startswith(word):
        wordlength=len(word)
        self.result.append(word)
        self.solve(characters[wordlength:characterslength])
        self.result.pop()

if __name__=="__main__":

  s=Solution()

  print "Test case 0:"
  characters=""
  dictionary=list()
  s.newDictionary(dictionary)
  s.solve(dictionary)

  print "Test case 1:"
  characters="catsanddog"
  dictionary=["cats","and","sand","dog","cat"]
  s.newDictionary(dictionary)
  s.solve(characters)

  print "Test case 2:"
  characters="aaa"
  dictionary=["a","aa","aaa"]
  s.newDictionary(dictionary)
  s.solve(characters)


结果
hadoop@dream:~/sohu$./last.py
Test case 0:
none
Test case 1:
cats and dog
cat sand dog
Test case 2:
a a a
a aa
aa a
aaa





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值