程序员面试金典(8):翻转子串(python)
题目描述
假定我们都知道非常高效的算法来检查一个单词是否为其他字符串的子串。请将这个算法编写成一个函数,给定两个字符串s1和s2,请编写代码检查s2是否为s1旋转而成,要求只能调用一次检查子串的函数。
给定两个字符串s1,s2,请返回bool值代表s2是否由s1旋转而成。字符串中字符为英文字母和空格,区分大小写,字符串长度小于等于1000。
测试样例:
"Hello world","worldhello "
返回:false
"waterbottle","erbottlewat"
返回:true
思路
以s1=ABCD为例,我们先分析s1进行循环移位之后的结果
ABCD->BCDA->CDAB->DABC->ABCD …
假设我们把前面移走的数据进行保留:
ABCD->ABCDA->ABCDAB->ABCDABC->ABCDABCD…..
因此看出,对s1做循环移位,所得字符串都将是字符串s1+s1的子字符串。
如果s2可以由s1循环移位得到,则一定可以在s1s1上。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by xuehz on 2017/8/21
class ReverseEqual:
def checkReverseEqual(self, s1, s2):
# write code here
if len(s2) != len(s1):
return False
for i in s2:
if i not in s1:
return False
return True
def checkReverseEqual1(self, s1, s2):
if len(s2) != len(s1):
return False
s = s1 + s1
if s.find(s2) == -1:
return False
return True
if __name__ == '__main__':
s1 = 'Hello world'
s2 = 'worldhello'
R = ReverseEqual()
print R.checkReverseEqual1(s1, s2)
>>>info = 'abca'
>>> print info.find('a') # 从下标0开始,查找在字符串里第一个出现的子串,返回结果:0
0
>>> print info.find('a',1) # 从下标1开始,查找在字符串里第一个出现的子串:返回结果3
3
>>> print info.find('3') # 查找不到返回-1
-1