【每日一题】CareerCup1.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 (e.g., "waterbottle" is a rotation of "erbottlewat").

解析:

  这道题一开始做的时候想法比较笨,一开始考虑的是将字符串拆分成字符数组然后再比较的办法,费时费力,说明自己实在是太水了,后来review了前辈们的答案,发现这道题的解题思路十分巧妙,我们设字符串s1和s2分别为"waterbottle"和"erbottlewat",这道题解题的关键在于,正确的使用题目给我们的函数isSubstring()。那么如何使用这个函数呢?显然给定的两个字符串不存在字串关系,因此我们的思路是将一个字符串变长,不妨构建一个为s1+s1的字符串,我们会发现其内容为“waterbottlewaterbottle”,红色的部分正好为原字符串s1的回转,问题得到解决。

  同时也应该注意到,长度不相等的两个字符串是无法构成回转的,因此长度也是需要预先检测的一个方面。

因此代码主要体现两方面的内容:

  1.两个字符串长度的比较

  2.运用isSubstring方法判断回转。

 

代码:

 

 1 /*Assume you have a method isSubstring which checks if one word is a substring of another. 
 2  * Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 
 3  * using only one call to isSubstring (e.g., "waterbottle" is a rotation of "erbottlewat").
 4  * */
 5 public class CareerCup_1_8 {
 6     public static boolean isSubstring(String s1, String s2){
 7         if (s1.contains(s2)) return true;
 8         else return false;
 9     }
10     public static boolean isRotation(String s1, String s2){
11         if (s1.length()!=s2.length()) 
12             return false;
13         else if ((s1+s1).contains(s2))
14             return true;
15         else return false;
16     }
17 }

 

 

PS: 另外看到一则大神关于字符串rotation的实现,果然我们还是太年轻……

https://github.com/1094401996/Programming--Pearls/blob/master/Chapter2/src/problemB__Rotation/Rotation.java

 

转载于:https://www.cnblogs.com/sayary/archive/2013/02/25/2932552.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值