Cracking the coding interview--Q1.8

题目

原文:

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---

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值