python算法 循环单词

单单单单点 2017-09-27 10:40:52
我在做一题lintcode上的字符串算法,题目是挺简单的,只是一直timeout,不知道该如何优化,有人帮我看下吗(本人实在是菜)
这是原网站:http://www.lintcode.com/zh-cn/problem/rotate-words/

我的代码如下:
# -*- coding: cp936 -*-
class Solution:
"""
@param: A: a string
@param: B: a string
@return: a boolean
"""

def countRotateWords(self, words):
# Write your code here
dic = {}
result = 0
flag = False
for word in words:
flag = False
lengh = len(word)
if dic.has_key(lengh):
for w in dic[lengh]:
if Solution.compare(word,w):
flag = True
else:
dic[lengh] = list()
if not flag:
dic[lengh].append(word)
result += 1


return result

@staticmethod
def compare(word1,word2):
if word1 != word2:
len1 = len(word1)
len2 = len(word2)
if len1 == len2:
for i in range(1,len1):
if word1 == Solution.stringMove(word2,i):
return True
return False
else:
return False
return True

'''此方法更慢
@staticmethod
def compare(word1,word2):
if word1 != word2:
len1 = len(word1)
len2 = len(word2)
if len1 == len2:
s = word1 + word1
if s.find(word2) != -1:
return True
return False
return True
'''
@staticmethod
def stringMove(A, n):
# write code here
alist = list(A)
result = []
lengh = len(alist)
if lengh <=0 :
return ''
for i in range(0,lengh):
result.append(alist[(i+n)%lengh])
return ''.join(result)


if __name__ == '__main__':
s = Solution()
# print s.compare('bbaa','abba')
print s.countRotateWords(["abba", "bbaa", "baab", "aabb", "abba"])



...全文
350 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Jason_o_0 2017-11-24
  • 打赏
  • 举报
回复
楼主这种解法在lintcode测评无法通过 在测评88%处有一组较大的测试数据 我改变了一下算法思路 代码如下:

class Solution:
    """
    @param: words: A list of words
    @return: Return how many different rotate words
    """
    def trans_word(self, word):
        word_list = [word]
        for c in range(len(word)):
            word = word[1:] + word[0]
            word_list.append(word)
        word_list.sort()
        return word_list[0]
        
    def countRotateWords(self, words):
        # Write your code here
        for i in range(len(words)):
            new_word = self.trans_word(words[i])
            words[i] = new_word
        return len(set(words))
sanGuo_uu 2017-09-28
  • 打赏
  • 举报
回复
引用 3 楼 hhf15980873586 的回复:
@sanGuo_uu 改了这句 if wordNew in wordTmp and len(wordNew) == len(wordTmp)/2: 就accept,看了你的方法才觉得我的思路有问题,循环太多,谢谢了 发现了 if wordNew in wordTmp 这种骚套路,惊讶!
是的,要加后面这个条件,不然逻辑不通——len(wordNew) == len(wordTmp)/2 这个版块是脚本语言(perl/python) 你看的这个做题网站也挺有意思的 python的思想之一就是要尽量写得简单。 循环多就会难理解
sanGuo_uu 2017-09-27
  • 打赏
  • 举报
回复
这里是python,不是java 和你说慢的那个,思路比较像。但我是秒出啊
#!/usr/bin/python
# -*- coding:utf-8 -*-

testWord=["picture", "turepic", "icturep", "word", "ordw", "lint"]

#print "picture" in "wordword"

def countRotateWords(words):
	res=[]
	for word in words:
		if res==[]:
			res.append(word)
			continue
		wordTmp=word+word
		flag=False
		for wordNew in res:
			if wordNew in wordTmp:
				flag=True
				break
		if flag==False:
			res.append(word)
	return res

result=countRotateWords(testWord)
print result
print len(result)
单单单单点 2017-09-27
  • 打赏
  • 举报
回复
@sanGuo_uu 改了这句 if wordNew in wordTmp and len(wordNew) == len(wordTmp)/2: 就accept,看了你的方法才觉得我的思路有问题,循环太多,谢谢了 发现了 if wordNew in wordTmp 这种骚套路,惊讶!
单单单单点 2017-09-27
  • 打赏
  • 举报
回复
为什么说这里是python不是java呢?能不能给我讲讲,我刚学python @sanGuo_uu

37,717

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧