1.9
string rotation
假定已知isSubstring(),可以判断s2是否是s1的字串; 定义:rotation, 旋转;
举例:
s1=waterbottle,
x=wat
y=erbottle
s2=erbottlewat
s1, s2是rotation关系
问题:能否使用一次isSubstring来判断rotation关系?
思路:
s3=s1+s1
isSubstring(s3,s2)=rotation
举例:
s1 = waterbottle
s2 = erbottlewat
s3=s1+s1=waterbottlewaterbottle
因为s3 和s2 是 subString的关系;
C#代码:
/// <summary>
/// 是否是旋转字符串
/// </summary>
/// <param name=" s1"></param>
/// <param name=" s2"></param>
/// <returns></returns>
public static bool IsRotation( string s1, string s2)
{
int len = s1.Length;
//检查长度是否相等,或者为空
if (len == s2.Length && len > 0)
{
string s3 = s1 + s1;
return IsSubstring(s3,s2)
}
//长度不等,或者长度为0,则返回false;
return false;
}
/// <summary>
/// s1是否包含s2
/// </summary>
/// <param name=" s1"></param>
/// <param name=" s2"></param>
/// <returns></returns>
private static bool IsSubstring( string s1, string s2)
{
return s1.Contains(s2);
}