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(!target||!source) return -1;
string A(source); int m;
string B(target); vector<int> v1;
// 截取字符串前三个字符
if (A.size() < B.size()) return -1;
else{
if (B.size() > 3){
for (int i = 0; i < A.size(); i++){
if (A[i] == B[0] && A[i + 1] == B[1] && A[i + 2] == B[2])
v1.push_back(i + 3);
}
if (v1.size() == 0) return -1;
for (auto c : v1){
for (m = 0; m < B.size()-3; m++)
if (A[c+m] != B[3+m]) break;
if (m == B.size()-3)
return c - 3;
}
}
else{
for (int i = 0; i < A.size() - B.size() + 2; i++){
for (m = 0; m < B.size() ; m++)
if (A[i+m] != B[m]) break;
if (m == B.size())
return i+m - B.size();
}
}
} return -1;
}
};
LintCode(easy)字符串查找
最新推荐文章于 2021-12-27 23:00:43 发布