459. Repeated Substring Pattern
2017-01-08 21:07
169 查看
题意:Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
Example 1:
Input: “abab”
Output: True
Explanation: It’s the substring “ab” twice.
Example 2:
Input: “aba”
Output: False
Example 3:
Input: “abcabcabcabc”
Output: True
Explanation: It’s the substring “abc” four times. (And the substring “abcabc” twice.)
思路:这题用两次循环一次去找使可以找到答案的,但是时间复杂度太高,所以其中一种方法是可以用KMP算法来做,只要求出next数组,next数组中包含了重复子字符串的信息即可,但是这又有个问题了,next数组的求取方法有很多种,但是对这题来说,太细化的next数组对这题是不适合的,具体可以看这篇博客KMP多种模式数组的比较(Python版代码),比如对于文中细化第二种的next数组求法(第一种更不适合,因为完全没有规律),T=’abad’和’abab’,对应的next数组都是’[-1,0,-1,1]’,而对于不细化的next数组求法,对应的next数组为’[-1,-1,0,-1]’和’[-1,-1,0,1]’,前一种对应的求next数组方法如下:
后一种对应的方法为:
利用后一种求next数组的方法,再加上以下代码就可以验证是否为重复字串:
当然,下面还有一种比较奇特的方法,因为对于串S重复子串至少重复一次,所以把该串第一个字符去掉构成S1,再把该串的最后一个字符去掉构成S2,则S1+S2构成的串肯定含有S,即:
可以写成:
Example 1:
Input: “abab”
Output: True
Explanation: It’s the substring “ab” twice.
Example 2:
Input: “aba”
Output: False
Example 3:
Input: “abcabcabcabc”
Output: True
Explanation: It’s the substring “abc” four times. (And the substring “abcabc” twice.)
思路:这题用两次循环一次去找使可以找到答案的,但是时间复杂度太高,所以其中一种方法是可以用KMP算法来做,只要求出next数组,next数组中包含了重复子字符串的信息即可,但是这又有个问题了,next数组的求取方法有很多种,但是对这题来说,太细化的next数组对这题是不适合的,具体可以看这篇博客KMP多种模式数组的比较(Python版代码),比如对于文中细化第二种的next数组求法(第一种更不适合,因为完全没有规律),T=’abad’和’abab’,对应的next数组都是’[-1,0,-1,1]’,而对于不细化的next数组求法,对应的next数组为’[-1,-1,0,-1]’和’[-1,-1,0,1]’,前一种对应的求next数组方法如下:
def getPrefix(needle): i, j, n = -1, 0, len(needle) next = [-1] * n while j < n - 1: if i == -1 or needle[i] == needle[j]: i, j = i + 1, j + 1 next[j] = i else: i = next[i] return next
后一种对应的方法为:
def getPrefix1(self, pattern): prefix = [-1] * len(pattern) j = -1 for i in xrange(1, len(pattern)): while j > -1 and pattern[j + 1] != pattern[i]: j = prefix[j] if pattern[j + 1] == pattern[i]: j += 1 prefix[i] = j return prefix
利用后一种求next数组的方法,再加上以下代码就可以验证是否为重复字串:
prefix = getPrefix(str) return prefix[-1] != -1 and (prefix[-1] + 1) % (len(str) - prefix[-1] - 1) == 0
当然,下面还有一种比较奇特的方法,因为对于串S重复子串至少重复一次,所以把该串第一个字符去掉构成S1,再把该串的最后一个字符去掉构成S2,则S1+S2构成的串肯定含有S,即:
def repeatedSubstringPattern(self, str): """ :type str: str :rtype: bool """ if not str: return False ss = (str + str)[1:-1] return ss.find(str) != -1
可以写成:
def repeatedSubstringPattern(self, str): return str in (2 * str)[1:-1]
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- 通过构建一个简单的掷骰子游戏去学习怎么用 Python 编程