算法刷题Day 9 找出字符串中第一个匹配项的下标+重复的子字符串

Day 9 字符串

28.找出字符串中第一个匹配项的下标

next数组写法

void getNext(int *next, const string &s)
{
    int j = 0;
    next[0] = 0;
    
    for (int i = 1; i < s.size(); i++)
    {
        while (j > 0 && s[i] != s[j]) // 前后缀不相同
        {
            j = next[j - 1]; // 往前回退
        }
        if (s[i] == s[j]) // 前后缀相同
        {
            j++;
        }
        next[i] = j; // 将j(前缀的长度)赋给next[i]
	}
}

整体

class Solution {
    void getNext(int *next, const string &s)
    {
        int j = 0;
        next[0] = 0;

        for (int i = 1; i < s.size(); i++)
        {
            while (j > 0 && s[j] != s[i]) 
            {
                j = next[j - 1];
            }
            if (s[j] == s[i])
            {
                j++;
            }
            next[i] = j;
        }
    }

public:
    int strStr(string haystack, string needle) {
        int j = 0;
        int next[needle.size()];
        getNext(next, needle);

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

        return -1;
    }
};

459. 重复的子字符串

暴力解法

class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        int totalLen = s.size();

        for (int i = 0; i < totalLen / 2; i++) // 超过一半即可退出循环
        {
            int len = i + 1;
            if (totalLen % len) continue;
            string subStr = s.substr(0, len);
            bool flag = true;
            for (int j = 0; j < totalLen; j += len)
            {
                string cmp = s.substr(j, len);
                if (cmp != subStr)
                {
                    flag = false;
                    break;
                }
            }
            if (flag) return true;
        }

        return false;
    }
};

移动匹配

class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        string ss = s + s;
        string cmp = ss.substr(1, ss.size() - 2);
        auto idx = cmp.find(s);
        return idx != cmp.npos;
    }
};

KMP算法

class Solution {
    void getNext(int *next, const string &s)
    {
        int j = 0; 
        next[0] = 0;
        for (int i = 1; i < s.size(); i++)
        {
            while (j > 0 && s[i] != s[j])
            {
                j = next[j - 1];
            }
            if (s[i] == s[j])
            {
                j++;
            }
            next[i] = j;
        }
    }

public:
    bool repeatedSubstringPattern(string s) {
        int len = s.size();
        int next[len];
        getNext(next, s);
        return next[len - 1] != 0 && (len % (len - next[len - 1]) == 0);
    }
};

你可能感兴趣的:(算法,leetcode,职场和发展)