yueyu_93 2017-05-20 09:38 采纳率: 0%
浏览 2245

内存错误(sysmalloc:assertion),求大神指点

class Solution {
public:
int strStr(string haystack, string needle) {
int hay_len = haystack.length();
int needle_len = needle.length();
int i = 0, j = 0;
int* next = new int[needle_len];
getNext(needle, next);
while(i < hay_len && j < needle_len){
if(j == -1 || haystack[i] == needle[j]){
++i;
++j;
}
else{
j = next[j];
}
}
if(j >= needle_len)
return i - j;
else
return -1;

}

public:
void getNext(string needle, int next[]){
int n = needle.length();
int j = -1;
int i = 0
next[0] = -1;
while(i < n) {
if (j == -1 || needle[i] == needle[j]) {
++i;
++j;
next[i] = j;
}
else
j = next[j];
}
}
};

  • 写回答

1条回答 默认 最新

  • wanwan_1996 2017-06-12 02:43
    关注
     # include <iostream>
    # include <cstring>
    # include <algorithm>
    using namespace std;
    
    int next_[100];
    
    void get_next(char *T)
    {
        int i = 1;
        int j = 0;
        next_[1] = 0;
        int len = strlen(T);
    
        while (i < len)
        {
            if (j == 0 || T[i] == T[j])
            {
                ++i;
                ++j;
                next_[i] = j;
            }
            else
            {
                j = next_[j];
            }
        }
        for (i = 0; i < len; i++)
        {
            cout << next_[i] << " ";
        }
        cout << endl;
    }
    
    bool KMP(char *S, char *T)
    {
        cout << "begin" << endl;
        int i = 1;
        int j = 1;
        int len_s = strlen(S);
        int len_t = strlen(T);
        while (i < len_s && j < len_t)
        {
            if (j == 0 || S[i] == T[j])
            {
                ++i;
                ++j;
            }
            else
            {
                j = next_[j];
            }
        }
        cout << j << endl;
        if (j >= len_t)
        {
            cout << "hello" << endl;
            return true;
        }
        else
            return false;
    }
    
    int main()
    {
        char S[100] = "0aaaaaaabcdefa";
        char T[100] = "0aaaabcd";
        next_[0] = 1;
        memset(next_, 0, sizeof(next_));
        get_next(T);
        bool k = KMP(S, T);
        cout << k << endl;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器