题目描述
实现str()函数。
给定一个haystack字符串和一个needle字符串,在haystack字符串中找出needle字符串出现的第一个位置(从0开始)。如果不存在,则返回-1。
示例
输入: haystack = "hello", needle = "ll"
输出: 2
我的思路
以haystack字符串为主,遍历haysack字符串分别以每个字符串为起点,嵌套遍历needle字符串,时间复杂度为O(m*n)。
class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.size();
int m = needle.size();
if(needle.empty()){
return 0;
}
int i = 0;
int j = 0;
for(i=0;i<=n-m;i++){
bool flag = true;
for(j=0;j<m;j++){
if(haystack[i+j] != needle[j]){
flag = false;
break;
}
}
if(flag) return i;
}
return -1;
}
};
更好的思路
可以考虑到灵活地使用substr函数,同样遍历haysack字符串分别以每个字符串为起点,截取needle大小的一段字符串分别与neddle字符串比较,减少了遍历neddle每一个字符串所花费的时间,时间复杂度O(n-m+1)。
class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.size();
int m = needle.size();
if(n == 0)
return 0;
if(m < n)
return -1;
for(int i = 0; i <= n - m; i++){
string subStr = n.substr(i, m);
if(subStr == needle)
return i;
}
return -1;
}
};
还有一种rolling hash的算法可以实现O(n)的时间复杂度具体参考rolling hash-Wikipedia。