Advertisement
Guest User

Untitled

a guest
Dec 22nd, 2014
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. /*
  2. * CC150 1.8
  3. * @author:Scarlett Chen
  4. * @date:12/22/2014 Mon 10:21 AM
  5. * 1.8 Assume you have a method isSubstring which checks if one word is a substring of another.
  6. * Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call
  7. * to isSubstring (e.g.,"waterbottle"is a rotation of"erbottlewat").
  8. * 先利用String本来的method写一个简单的isSubstring
  9. *
  10.  
  11. */
  12. public class IsRotation {
  13. //看了别人的思路写的~
  14. //把rotation之后的s2再连上一个s2,如果s2是rotation的话,那么原字符串s1就必然是s2的substring
  15. //Time:o(n) Space O(1)
  16. public boolean isRotation(String s1,String s2) {
  17. if (s1==null && s2==null) return true;
  18. if (s1==null || s2==null) return false;
  19. int len1 = s1.length();
  20. int len2 = s2.length();
  21. if (len1 !=len2) return false;
  22.  
  23. //核心代码
  24. return isSubstring(s1,s2+s2);
  25. }
  26.  
  27. //一开始自己想的方法
  28. //Time: O(n^2),需要遍历每一个字符(o(n))。把s2里的每一个字符作为s1的开头,试着看能不能对得上(复制两个substring其实又是o(n))。
  29. //实际上in worst case, call了n次isSubstring.
  30. //不好。
  31. public boolean isRotation_Bad(String s1, String s2) {
  32. if (s1==null && s2==null) return true;
  33. if (s1==null || s2==null) return false;
  34. int len1 = s1.length();
  35. int len2 = s2.length();
  36. if (len1 !=len2) return false;
  37.  
  38. //核心代码
  39. for (int i=0; i<len2; i++) {
  40. String latterHalf = s2.substring(i);
  41. if (isSubstring(latterHalf,s1))
  42. if ((latterHalf+s2.substring(0, i)).equals(s1)) return true;
  43. }
  44. return false;
  45. }
  46.  
  47. // The assumed given method
  48. public static boolean isSubstring(String sub, String s) {
  49. return (s.indexOf(sub)!=-1)?true: false;
  50. }
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement