首页 > 试题广场 >

翻转子串

[编程题]翻转子串
  • 热度指数:26945 时间限制:C/C++ 3秒,其他语言6秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

给定2个字符串s1和s2,请判断s2是否为s1旋转而成,返回bool值。字符串中字符为英文字母和空格,区分大小写,字符串长度小于等于1000。


测试样例:
"Hello world","worldhello "
返回:false
"waterbottle","erbottlewat"
返回:true

Python one line solution:

return set(s1)==set(s2)
发表于 2017-10-01 20:19:58 回复(2)
没有用到检查子串的函数,没想出来出题者的意图
class ReverseEqual:
	def checkSubstr(selk, s1, s2): #s2 is substr of s1
		dis, j = 0, 0
		for i in range(len(s1)):
			if j == len(s2):
				break
			if s1[i] == s2[j]:
				dis += 1
				j += 1
			else:
				dis = 0
				j = 0
		if dis == len(s2):
			return True
		else:
			return False
	def checkReverseEqual(self,s1,s2):
		if len(s1) != len(s2):
			return False
		for i in range(len(s1)):
			temp = s1[i:] + s1[:i]
			if temp == s2:
				return True
		return False

发表于 2016-10-09 12:57:02 回复(0)
从例子入手:
x = 'abc', y = 'def'
S1 = x + y = xy = 'abcdef'
S2 = y + x = yx = 'defabc'
那么S1 + S1 = x + y + x + y = xyxy = 'abcdefabcdef'
S2 如果由S1旋转而成,那么S2 肯定是 S1S1的字串, yx 肯定是 xyxy 字串
# -*- coding:utf-8 -*-
class ReverseEqual:
    def checkReverseEqual(self, s1, s2):
        return s2 in s1 + s1

发表于 2016-08-01 20:54:52 回复(0)

问题信息

难度:
3条回答 32806浏览

热门推荐

通过挑战的用户

查看代码