搜狐-笔试题


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

题目大意

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

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

输出所有的句子.


比如:

字符序列 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





你可能感兴趣的:(算法)