只想到用暴力解, 兩個迴圈去掃描字串
public:
/*
* @param source: source string to be scanned.
* @param target: target string containing the sequence of characters to match
* @return: a index to the first occurrence of target in source, or -1 if target is not part of source.
*/
int strStr(const char *source, const char *target) {
// write your code here
if (NULL == source || NULL == target) {
return -1;
}
if ('\0' == *source && '\0' == *target) {
return 0;
}
int srcIdx = 0;
while ('\0' != source[srcIdx]) {
bool isMatch = true;
int srcTestIdx = srcIdx, tgtIdx = 0;
while ('\0' != target[tgtIdx]) {
if (target[tgtIdx] != source[srcTestIdx]) {
isMatch = false;
break;
}
srcTestIdx++;
tgtIdx++;
}
if (isMatch) {
return srcIdx;
}
srcIdx++;
}
return -1;
}
};
沒有留言:
張貼留言