2014.2.28 02:38
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
Solution1:
The first one is brute-force, reference is from source code of strstr() in <string.h>.
Total time complexity is O(n * m). Space complexity is O(1).
Accepted code:
1 // 1WA, 1AC, standard Brute-Force solution. 2 #include <cstring> 3 using namespace std; 4 5 class Solution { 6 public: 7 char *strStr(char *haystack, char *needle) { 8 const char *ptr = haystack; 9 size_t len = strlen(needle); 10 if (len == 0) { 11 return haystack; 12 } 13 while ((ptr = strchr(ptr, *needle)) != nullptr) { 14 if (strncmp(ptr, needle, len) == 0) { 15 return (char *)ptr; 16 } 17 ++ptr; 18 } 19 } 20 };
Solution2:
This solution uses KMP Algorithm, which runs in linear time.
The key difference between KMP and Brute-Force is the "next" array, that defines the position to backtrack when mismatch happens.
Here is the reference from Wikipedia of KMP Algorithm, if you'd like to learn more about it.
Total time complexity is O(len(haystack) + len(needle)). Space complexity is O(needle).
Accepted code:
1 // 2CE, 1RE, 1WA, 1AC, KMP Algorithm 2 #include <cstring> 3 #include <vector> 4 using namespace std; 5 6 class Solution { 7 public: 8 char *strStr(char *haystack, char *needle) { 9 if (haystack == nullptr || needle == nullptr) { 10 return nullptr; 11 } 12 lp = strlen(needle); 13 lw = strlen(haystack); 14 15 if (lp == 0) { 16 return haystack; 17 } 18 19 if (lw < lp) { 20 return nullptr; 21 } 22 23 calculateNext(needle); 24 char *result = KMPMatch(haystack, needle); 25 next.clear(); 26 27 return result; 28 } 29 int lp; 30 private: 31 int lw; 32 vector<int> next; 33 34 void calculateNext(char *pat) { 35 int i = 0; 36 int j = -1; 37 38 next.resize(lp + 1); 39 next[0] = -1; 40 while (i < lp) { 41 if (j == -1 || pat[i] == pat[j]) { 42 ++i; 43 ++j; 44 next[i] = j; 45 } else { 46 j = next[j]; 47 } 48 } 49 } 50 51 char* KMPMatch(char *word, char *pat) 52 { 53 int index; 54 int pos; 55 56 index = pos = 0; 57 while (index < lw) { 58 if (pos == -1 || word[index] == pat[pos]) { 59 ++index; 60 ++pos; 61 } else { 62 pos = next[pos]; 63 } 64 65 if (pos == lp) { 66 // the first match is found 67 return word + (index - lp); 68 } 69 } 70 71 return nullptr; 72 } 73 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)