cracking the coding interview No1.8

1.8Assume 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 onw call to is

Substring (eg,”waterbottle” is a rotation of “erbottlewat”.)

Answer:

//C语言风格
bool judge(char *str1,char *str2)
{
	if (str1 == NULL || str2 == NULL)
		return false;

	char *str3 = str1;
	char *str4 = str1;
	while (*str1++);
	while (*str1++=*str3++);//连接str1和str3
	*str1 = '\0';
	while (*str4!='\0')
	{
		char *str5 = str2;
		while (*str4++ == *str5++ )
		{
			if (*str5 == '\0')
				return true;
		}
		str4++;
	}
	return false;
}

//Java简洁的代码
public static boolean isRotation(String s1, String s2) {
	int len = s1.length();
	/* check that s1 and s2 are equal length and not empty */
	if (len == s2.length() && len > 0) { 
		/* concatenate s1 and s1 within new buffer */
		String s1s1 = s1 + s1;
		return isSubstring(s1s1, s2);
	}
	return false;
}


你可能感兴趣的:(cracking the coding interview No1.8)