Posted on

Description

Submission 1

class Solution {
public:
    int strStr(string haystack, string needle) {
        return haystack.find(needle);
    }
};

Submission 2

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.empty()) return 0;
        for(int i = 0; i < haystack.size(); ++i) {
            if(haystack.size() - i < needle.size()) return -1;
            if(haystack[i] == needle[0]) {
                int j = 0;
                for(; j < needle.size(); ++j) {
                    if(haystack[i + j] != needle[j]) break;
                }
                if(j == needle.size()) return i;
            }
        }
        return -1;
    }
};

Submission 3 – 210204

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.empty()) return 0;
        if(needle.length() > haystack.length()) return -1;

        for(int i = 0; i < haystack.size(); ++i) {
            if(i + needle.size() > haystack.size()) break;
            int beg = i, j = 0;
            for(; j < needle.size(); ++j) {
                if(haystack[i+j] != needle[j]) break;
            }
            if(j == needle.size()) return beg;
        }
        return -1;
    }
};

Submission 210420

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.empty()) return 0;
        int h = haystack.size();
        int n = needle.size();
        for(int i = 0; i <= h - n; ++i) {
            for(int j = 0; j < n; ++j) {
                if(haystack[i+j] != needle[j]) break;
                else if(j == n - 1) return i;
            }
        }
        return -1;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *