C++ 子串匹配主串

暴力匹配

#include <iostream>
#include <string>
using namespace std;

int strTsr(string haystack, string needle)
{
    if (needle.empty())
        return 0;

    int n = haystack.size();
    int m = needle.size();

    for (int i = 0; i < n; ++i)
    {
        int pos = i;
        for (int j = 0; j < m; ++j)
        {
            if (needle[j] != haystack[pos++])
            {
                break;
            }
            else
            {
                if (j == (m - 1))
                {
                    return i;
                }
            }
        }
    }
    return -1;
}

int main()
{

    int asn = strStr("ABCDABCDE", "ABCDE");

    if (asn == 0)
    {
        cout << "匹配的子串为空!" << endl;
    }
    else if (asn == -1)
    {
        cout << "子串不匹配主串!" << endl;
    }
    else
    {
        cout << "子串匹配了主串,开始位置:" << asn << endl; 
    }
    

    return 0;
}


上一篇:LeetCode刷题day44


下一篇:约和review