此代码适用于我的计算机,但不适用于leetcode

时间:2018-06-02 21:05:20

标签: python algorithm python-2.7

我正试图解决这个leetcode问题。我在笔记本电脑上运行它时输出正常,但是当我将它提交给leetcode时却没有。花了一个小时仍然无法弄清楚。结合更多的眼睛肯定会有所帮助。

class Solution28(object):
def replaceWords(self, dict, sentence):
    """
    :type dict: List[str]
    :type sentence: str
    :rtype: str
    """
    dict=sorted(dict)
    slist=sentence.split(' ')
    #print slist
    n = len(slist)
    for i in xrange(n):
        for d in dict:
            if d in slist[i]:
                slist[i]=d
                break
            elif d > slist[i]:
                break
    return " ".join(slist)

obj = Solution28()
print obj.replaceWords(["cat", "bat", "rat"],"battery cattle was rattled by the battery")
####o/p from my laptop: bat cat was rat by the bat
####o/p in leetcode: battery cat was rat by the battery

1 个答案:

答案 0 :(得分:3)

当单词不在开头时,此代码中存在算法错误。

例如,此代码会认为“rat”是“mouserat”的根。

但是,如果您更改该行:

<div>
    {
      props.projects.map( project => (
        <div>
          <p>{project.title}</p>
          <img src={project.image} />
        </div>
      ) )
    }
</div>

if d in slist[i]:
当我在leetcode中测试时,它对我来说很好。