英文:
Bool condition checks gives warning
问题
我正在尝试解决一个问题,链接在 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 循环中,我两个检查都有一个布尔结果。有人可以帮助我理解吗?
谢谢。
英文:
I am trying to solve a problem here https://leetcode.com/problems/word-break/ . My code looks like below:-
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;
}
};
This gives me a error 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
I am not sure what is wrong here as both my checks in the if loop on that line have a bool outcome. Can someone help me understand it ?
Thanks
答案1
得分: 1
你正在检查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))
英文:
you are checking if dict[j]
is true
and if j
is equal to str_size
, however,the problem occurs when j
becomes equal to str_size
, so I think you must modify the loop condition to j < str_size
instead of j <= str_size
because it ensures you the j
remains within the bounds of the dict
array!
so fix it like below :
if ((dict[j] == true) && (j == str_size - 1))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论