题目描述
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题目大意:字符串查找,查到返回第一次找到的下标,找不到返回-1。needle为空时返回0
样例
Example 1:
Input: haystack = “hello”, needle = “ll”
Output: 2
Example 2:
Input: haystack = “aaaaa”, needle = “bba”
Output: -1
python解法
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
return haystack.find(needle);
Runtime: 36 ms
Memory Usage: 13.8 MB
题后反思:
- python、java、C++等高级语言都实现了字符串查找这一功能
C语言解法
int strStr(char * haystack, char * needle){
int len_b = strlen(needle);
int len_a = strlen(haystack);
if (len_a < len_b) return -1;
for (int i = 0; i <= len_a-len_b; ++i) {
int j = 0;
while(j < len_b && haystack[j+i] == needle[j]) {
j++;
}
if (j == len_b) {
return i;
}
}
return -1;
}
Runtime: 4 ms, faster than 82.13% of C online submissions for Implement strStr().
Memory Usage: 7.3 MB, less than 30.83% of C online submissions for Implement strStr().
题后反思:
- 用字符串长度做判断条件,可以直接规避数组越界的错误。
- 用’\0’做判断条件,需要时刻注意数组越界。
文中都是我个人的理解,如有错误的地方欢迎下方评论告诉我,我及时更正,大家共同进步