本周題目難度級別"Easy"
題目:給你兩個字符串haystack和needle见秤,讓你找出needle在haystack中的開始的位置黎泣,若沒有就返回-1
思路很簡單,就是一個一個的比較,實現(xiàn)起來也比較簡單勘究,我就不寫注釋了,當(dāng)然斟冕,效率太低沒什么參考價值也是一個原因口糕。
int strStr(char* haystack, char* needle) {
if (strlen(needle) < 1) {
return 0;
}
if (strlen(haystack) < 1) {
return -1;
}
int result = -1;
int i,j,k;
for (i = 0; i < strlen(haystack); i ++) {
if (haystack[i] == needle[0]) {
result = i;
for (j = i; (j - i) < strlen(needle); j++) {
if (i == j) {
if ((strlen(haystack) - j) < (strlen(needle))) {
return -1;
}
}
if (haystack[j] != needle[j-i]) {
result = -1;
if ((i + strlen(needle)) > strlen(haystack)) {
return result;
}
break;
}
}
if (result != -1) return result;
}
}
return result;
}
需要說明的一點是,這是一道非常經(jīng)典的題目磕蛇,由此引出了KMP算法景描,這個KMP算法已經(jīng)有很多文章了,有興趣的朋友自己搜索學(xué)習(xí)即可秀撇。