Check if a string is a rotation of another string

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

My initial thoughts:
After some thinking, I finally crack this out: just to check whether s2 is a substring of s1 + s1.

My initial codes (solution):

	public static boolean isRotation(String s1, String s2) {
		if(s1.length() != s2.length()) return false;
		
		String duplicate = s1 + s1;
		return duplicate.contains(s2);
	}

Comments: I did forget the highlighted line when first writing this code. Apparently “aba” is not a rotation of “ab”, but “aba” indeed is the substring of “abab”. So, again, edge cases matter a lot.

Advertisements

1 Comment (+add yours?)

  1. Kinshuk
    May 01, 2014 @ 06:46:06

    Here is my code in java from http://k2code.blogspot.in/2011/12/how-will-you-check-if-s1-is-rotated.html :

    boolean isRotation(String s1,String s2) {
     return (s1.length() == s2.length()) && ((s1+s1).indexOf(s2) != -1);
    }
    

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: