码迷,mamicode.com
首页 > 其他好文 > 详细

[CTCI] String Rotation

时间:2017-06-20 13:36:52      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:water   dev   style   orm   call   word   run   split   string   

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

标签:water   dev   style   orm   call   word   run   split   string   

原文地址:http://www.cnblogs.com/lz87/p/7053581.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!