classSolution {public:intstrStr(string haystack,string needle) {if(needle =="") return0;int pos=0;for(; pos<haystack.length(); pos++) {if(haystack[pos] ==needle[0]) { string candidate =haystack.substr(pos,needle.length());if(candidate == needle) break; } }return pos ==haystack.length() ?-1: pos; }};// check at each char == first char of needle if the needle is in haystack
這樣實作的效率很差:
Runtime: 56 ms, faster than 23.21% of C++ online submissions for Implement strStr(). Memory Usage: 645.8 MB, less than 5.03% of C++ online submissions for Implement strStr().
如果換個實作方式,可以大幅提高效率:
classSolution {public:intstrStr(string haystack,string needle) {int m =haystack.size(), n =needle.size();for (int i =0; i <= m - n; i++) {int j =0;for (; j < n; j++) {if (haystack[i + j] !=needle[j]) {break; } }if (j == n) {return i; } }return-1; }};