1.9 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 (e.g., "waterbottle" is a rotation of "erbottlewat").

Hint
  • If a string is a rotation of another, then it's a rotation at a particular point. For example, a rotation of waterbottle at character 3 means cutting waterbottle at character 3 and putting the right half (erbottle) before the left half (wat).
  • We are essentially asking if there's a way of splitting the first string into two parts, x and y, such that the first string is xy and the second string is yx. For example, x = wat and y = erbottle. The first string is xy = waterbottle. The second string is yx = erbottlewat.
  • Think about the earlier hint. Then think about what happens when you concatenate erbottlewat to itself. You get erbottlewaterbottlewat.
Solution

本题给定两个字符串,让我们判断其中一个字符串是否为另一个的旋转字符串,此外还给了一个isSubstring函数来调用,不过规定只能调用一次。这里可以发现一个规律,若将一个字符串重复拼接,假如另一个字符串是拼接后字符串的子串,则它们就互为旋转字符串。
令 x = wat, y = erbottle
若有 s1 = xy, s2 = yx,显然它们互为旋转字符串
重复拼接 s1s1 = xyxy, 则可以看到 s2 为 s1s1 的子串

public boolean isStringRotation(String s1, String s2) {
    if (s1 == null || s2 == null || s1.length() != s2.length()) return false;
    return isSubstring(s1 + s1, s2);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,919评论 0 38
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,514评论 0 13
  • 愿有人陪你颠沛流离 单身或谈恋爱其实都不重要 有个人陪着 就认真去爱 没有的话 就好好照顾自己 青春是用来脱贫的 ...
    Aio大雄阅读 275评论 0 1
  • 秋天的一个早晨,来到许久不曾来过的河滩边,散步的时候没忘用手机东拍一下西拍一下。在跑道边露天座椅休息查看这些照片时...
    海松_0283阅读 272评论 0 1