长颈鹿Giraffe

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

原文:

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 ( i.e., “waterbottle” is a rotation of “erbottlewat”).

译文:

假设你有一个isSubstring函数,可以检测一个字符串是否是另一个字符串的子串。 给出字符串s1和s2,只使用一次isSubstring就能判断s2是否是s1的旋转字符串, 请写出代码。旋转字符串:"waterbottle"是"erbottlewat"的旋转字符串。

解答:

如果s1是s2的旋转字符串,那么我们一定能找到一个切割点将s1分割成xy,并且yx等于s2。例如:

s1 = xy = waterbottle
x = wat
y = erbottle
s2 = yx = erbottlewat

那么我们可以知道yx一定是xyxy的一个子串,也就是说,s2一定是s1s1的子串。所以这个题目的解法也就一目了然了。

public class Main {

    public static boolean isSubstring(String s1, String s2) {
        if(s1 == null || s2 == null)
            return false;
        if(s1.contains(s2))
            return true;
        else
            return false;
    }
    
    public static boolean isRotation(String s1, String s2) {
        return isSubstring(s1+s1,s2);
    }

    public static void main(String args[]) {
        String s1 = "waterbottle";
        String s2 = "erbottlewat";
        System.out.println(isRotation(s1,s2));
    }
}

 

 

posted on 2013-07-12 17:49  长颈鹿Giraffe  阅读(238)  评论(0编辑  收藏  举报