题目:
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