cracking the coding interview No1.8

来源:互联网 发布:suse linux 安装gcc 编辑:程序博客网 时间:2024/05/20 10:52

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;}


0 0
原创粉丝点击