[CTCI] String Rotation

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[CTCI] String Rotation相关的知识,希望对你有一定的参考价值。

Assume you have a method isSubstring which checks if one word is a substring of another.

Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring.

For example, "waterbottle" is a rotation of "erbottlewat".

 

An obvious solution is to get all s1.length() rotations of s1 in O(n^2); then check if each rotation is the same with s2 in O(n) time.

The runtime is O(n^3), which is very inefficient.

 

The BCR of this problem is O(n). Can you achieve this run time? 

Observation: for a string that is rotated,  there is a "split line". If s1 = x + y, then all rotations of s1 have the form of y + x; 

yx is a substring of xyxy, which is s1s1. 

 

Based on the above observation, we can develop a smart O(n) algorithm. Just call isSubstring(s1 + s1, s2). 

 

以上是关于[CTCI] String Rotation的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 在已旋转未知次数的n个整数的递增顺序排序数组中查找元素。 #searching #CtCI

Array Left Rotation

刷算法题网站

一些算法刷题的网站

简单循环时间复杂度内的递归函数

在 Spark Scala 中将 RDD[(String, String, String)] 转换为 RDD[(String, (String, String))]