布尔条件检查给出警告

问题描述 投票:0回答:1

我试图在这里解决一个问题https://leetcode.com/problems/word-break/。我的代码如下所示:-

bool existsInDict(string s, vector<string>& wordDict)
{
    if(std::find(wordDict.begin(),wordDict.end(),s) != wordDict.end())
    {
        return true;
    }
    return false;
}

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        int str_size = s.length();
        if(str_size == 0)
        return true;

        bool *dict = new bool[str_size+1];
        std::fill(dict, dict+str_size,false);

        for(int i =1;i<=str_size;++i)
        {
            if(dict[i]==false && existsInDict(s.substr(0,i),wordDict))
            {
                dict[i] = true;
            }
            if(dict[i]==true)
            {
                if(i==str_size)
                return true;
                for(int j=i+1;j<=str_size;++j)
                {
                    if((dict[j]==false) && existsInDict(s.substr(i+1,j-i),wordDict))
                    {
                        dict[j] = true;
                    }
                    if((dict[j]==true) && (j == str_size))
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }
};

这给了我一个错误

Line 40: Char 25: runtime error: load of value 190, which is not a valid value for type 'bool' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:49:25

我不确定这里出了什么问题,因为我在该行 if 循环中的两次检查都有布尔结果。有人可以帮我理解吗?

谢谢

c++ algorithm dynamic-programming
1个回答
0
投票

您正在检查

dict[j]
是否为
true
以及
j
是否等于
str_size
,但是,当
j
等于
str_size
时,就会出现问题,所以我认为您必须将循环条件修改为
j < str_size
而不是
j <= str_size
,因为它可以确保
j
保持在
dict
数组的范围内!

if ((dict[j] == true) && (j == str_size - 1))
© www.soinside.com 2019 - 2024. All rights reserved.