【发布时间】:2020-11-19 11:49:39
【问题描述】:
https://leetcode.com/problems/decode-ways/
我的解决方案:
class Solution {
public:
int numDecodings(string s) {
vector<int> dp(s.size(),0);
for(int i=0;i<s.size();i++)
{
int x =0;
if(s[i]-'0'>0 && s[i]-'0'<=9)
{
x = (i>0)? dp[i-1]:1;
}
if(i!=0 && stoi(s.substr(i-1,2))<=26)
{
cout<<i<<" ";
x = x + (i>=2 )? dp[i-2]:1;
}
dp[i] =x;
}
return dp[s.size()-1];
}
};
运行此代码会出现此错误
Line 924: Char 34: runtime error: addition of unsigned offset to 0x602000000010 overflowed to 0x60200000000c (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/stl_vector.h:933:34
我的问题是条件运算符在 (i>=2 ) 中评估 dp[i-2] 吗? dp[i-2]:1; 即使条件不满足?用普通的 if-else 替换它解决了我的问题。
【问题讨论】:
-
我建议您尝试使用您显示的代码创建一个minimal reproducible example,然后您可以轻松地使用调试器来单步调试代码并自己查看任何问题。为了帮助您,我还建议您简化复杂表达式,以便您可以看到复杂表达式中使用的中间值,以及使用
if-else而不是条件表达式。 -
嗯,不。
condition ? true_result() : false_result()只评估true_result()或false_result()之一。但是您的问题是对运算符优先级x = x + (i >= 2) ? dp[i-2] : 1的误解,它等同于x = (x + (i >= 2)) ? dp[i-2] : 1- 请注意额外的一对()。如果x最初为非零,则dp[i-2]可以评估为i < 2,这显然不是您所期望的 - 并且会给出未定义的行为。
标签: c++ if-statement operators conditional-operator