题目:
Problem Statement
For a given source string and a target string, you should output the first
index(from 0) of target string in source string.
If target does not exist in source, just return -1.
Example
If source = "source" and target = "target", return -1.
If source = "abcdabcdefg" and target = "bcd", return 1.
Challenge
O(n2) is acceptable. Can you implement an O(n) algorithm? (hint: KMP)
Clarification
Do I need to implement KMP Algorithm in a real interview?
Not necessary. When you meet this problem in a real interview, the interviewer may just want to test your basic implementation ability. But make sure your confirm with the interviewer first.
答案一:
int strStr(char* haystack, char* needle) {
if (haystack == NULL || needle == NULL) return -1; //空字符串,错误
const int len_h = strlen(haystack); //获取源字符串长度(strlen()函数要调用string.h头文件)
const int len_n = strlen(needle); //获取目标字符串长度
for (int i = 0; i < len_h - len_n + 1; i++) {
int j = 0;
for (; j < len_n; j++) {
if (haystack[i+j] != needle[j]) {
break;
}
}
if (j == len_n) return i;
}
return -1;
}
代码风格:
1、运算符==两边应加空格
2、变量名不要起s1``s2这类,要有意义,如target``source
3、Java 代码的大括号一般在同一行右边,C++ 代码的大括号一般另起一行
4、int i, j;`声明前有一行空格,是好的代码风格
是否在for的条件中声明i,j,这个视情况而定,如果需要在循环外再使用时,则须在外部初始化,否则没有这个必要。