strStr
2016-09-15 本文已影响0人
一枚煎餅
![](https://img.haomeiwen.com/i2985746/e975168624ac4b96.png)
===================== 解題思路 =====================
基本的 nesting for loop 檢查從 source 的每一個字符為起點 能否與 target 成功比對, 第二層的 for loop 容易忘記 source 的起點是 i + j 而 target 永遠是 j 為起點 ( 從頭開始比 ), 另外就是對 source or target 可能是 nullptr 的情況在開頭先檢查一次, 另外也可以用 memcpy 來取得 substr 進行 strcmp 的比對, 但是基本上沒有太大的差別
===================== C++ code ====================
<pre><code>//first solution
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) {
if(source == nullptr || target == nullptr) return -1;
int n1 = strlen(source), n2 = strlen(target);
int i, j;
for(i = 0; i <= n1 - n2 + 1; i++)
{
for(j = 0; j < n2; j++)
{
if(source[i+j] != target[j]) break;
}
if(j == n2) return i;
}
return -1;
}
};
//second solution (use memcpy to get substr)
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) {
if(source == NULL || target == NULL) return -1;
int len_A = strlen(source);
int len_B = strlen(target);
for(int i = 0; i <= len_A - len_B; i++)
{
char tmp[len_B];
memcpy( tmp, &source[i], len_B );
tmp[len_B] = '\0';
if(strcmp(tmp , target) == 0) return i;
}
return -1;
}
};<code><pre>