您的位置:首页 > 其它

Cracking the coding interview--Q1.8

2014-01-27 16:40 260 查看
题目

原文:

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的旋转字符串)

解答

首先需要理解旋转字符串,只是部分字符左右旋转,原来的字母顺序可以说是不变的。而且题目要求只能使用一次isSubstring方法,显然在原字符串判断是不可能的。可以通过加长原字符串来判断,如:s1="apple", s2="pleap",将s1加长,两个s1相加,s1+s1="appleapple",则s2明显是s1+s1的子串,由此可得:

class Q1_8{
public static boolean isRotation(String str1,String str2){
if(str1.length()!=str2.length()||str1.length()<=0)
return false;
return isSubString(str1+str1,str2);
}
public static boolean isSubString(String str1,String str2){
return str1.contains(str2);
}
public static void main(String[] args){
String s1="apple";
String s2="pleap";
System.out.println(isRotation(s1,s2));
}
}
此题若有更好的方法,还望指教!

---EOF---
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: