您的位置:首页 > 其它

LintCode: strStr

2016-01-07 11:26 218 查看
C++

(1) null

(2) length is 0

(3) return value

(4) strlen

class Solution {
public:
/**
* Returns a index to the first occurrence of target in source,
* or -1  if target is not part of source.
* @param source string to be scanned.
* @param target string containing the sequence of characters to match.
*/
int strStr(const char *source, const char *target) {
// write your code here
if (source == NULL || target == NULL) return -1;

int i, j, len_s = strlen(source), len_t = strlen(target);

if (len_s == 0 && len_t == 0) return 0;

i = 0;
while (source[i] != '\0') {
if (i + len_t > len_s) return -1;
j = 0;
while (target[j] != '\0') {
if (source[i + j] == target[j]) {
j++;
} else {
break;
}
}
if (target[j] == '\0')  return i;
i++;
}
return -1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: