标签: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).
标签:water dev style orm call word run split string
原文地址:http://www.cnblogs.com/lz87/p/7053581.html