为什么我在这里得到一个内存相关的错误

Why did I get a Memory-related error here?

本文关键字:内存 一个 错误 在这里 为什么      更新时间:2023-10-16

我遇到了一个来自网站的问题。给定string, sst,我必须找到sst的所有可能组合。例如,

s      = "doomdogged"
st     = "dg"
answer = 4

我可以从0或4中选择d,从6或7中选择g。这给了我4种可能的组合。

下面是我的代码:

#include <iostream>
#include <vector>
using namespace std;
string s, st;
bool target[26];
vector<int> positions[26];
vector<vector<int>> possibleCombinations;
void DFS_Enumeration(int, vector<int>*);
int DFS_index_max = 0;
int main(int argc, char *argv[])
{
    int    answer = 0;
    cin >> s;  //Given a string s
    cin >> st; //Given a string st
    //Find all possible combination of st in s
    for ( int i = 0 ; i < 26 ; ++ i )
        target[i] = 0;
    for ( int i = 0 ; i < st.length() ; ++ i )
        target[st[i] - 97] = 1;
    for ( int i = 0 ; i < 26 ; ++ i )
    {
        if ( target[i] == 0 ) continue;
        for ( int j = 0 ; j < s.length() ; ++ j )
        {
            if ( s[j] == i + 97 ) positions[i].push_back(j);
        }
    }
    DFS_index_max = st.length();
    vector<int> trail(0);
    DFS_Enumeration(0, &trail); //Here I got an runtime error
    for ( vector<int> vi : possibleCombinations )
    {
        int currentMax = 0;
        for ( int i = 0 ; i < vi.size() ; ++ i )
        {
            if ( vi[i] > currentMax )
            {
                if ( i == vi.size() - 1 ) ++ answer;
                currentMax = vi[i];
                continue;
            }
            else
                break;
        }
    }
    cout << answer;
}
void DFS_Enumeration(int index, vector<int>* trail)
{
    if ( index == DFS_index_max )
    {
        possibleCombinations.push_back(*trail);
        return;
    }
    for ( int i = 0 ; i < positions[st[index] - 97].size() ; ++ i )
    {
        trail -> push_back(positions[st[index] - 97][i]);
        DFS_Enumeration(++index, trail);
        trail -> pop_back();
    }
    return;
}

首先,我在st中查找字符,并根据需要标记它们,以便在我的布尔数组目标中找到。

然后,使用DFS枚举所有可能的组合。对于上面的"doom顽强"answers"dg"的例子,d存在于0、4、9中。g存在于6和7中。我将得到06、07、46、47、96、97。

最后,我计算那些有意义的,并输出答案。由于某种原因,我的代码不能工作,并在我标记的行生成一个关于内存的运行时错误。

DFS_Enumeration可能会将index递增任意次数,因此st[index]可能会超过字符串st的末尾。

相关文章: