为什么我不能将 size() 函数编写为 while 循环中的条件?
Why can't I write the size() function as a condition in the while loop?
当我学习KMP算法时。我发现如果我在 while 循环中将 size(( 函数编写为条件,我会得到错误的结果。
我发现如果我将 size(( 函数设置为条件。它不能第二次进入 while 循环。
例如,如果haystack="hello"和needle="ll"。正确答案是2。但是在此代码中。结果我得到 -1。因为我第一次进入时发现循环。j 的值变为"-1"。但是 i 的值仍然小于 haystack.size((,而 j 的相同时间值仍然小于 needle.size((。
为什么我不能以这种形式编写代码。
这是我的代码:
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.size() > haystack.size())
return -1;
if (haystack == "" || needle == "")
return 0;
std::vector<int> next(needle.size(), 0);
getNext(next, needle);
int i = 0, j = 0;
while (i < haystack.size() && j < needle.size()) // it is question location
{
if (j == -1 || haystack[i] == needle[j])
{
i++;
j++;
}
else
j = next[j];
}
if (j == needle.size())
return i - j;
else
return -1;
}
void getNext(std::vector<int>& next, string needle)
{
next[0] = -1;
int i = 0, j = -1;
while (i < needle.size()-1)
{
if (j == -1 || needle[i] == needle[j])
{
++i;
++j;
next[i] = j;
}
else
j = next[j];
}
}
};
如果我写这段代码。这是正确的
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.size() > haystack.size())
return -1;
if (haystack == "" || needle == "")
return 0;
std::vector<int> next(needle.size(), 0);
getNext(next, needle);
int i = 0, j = 0;
int p = haystack.size();//look at this
int q = needle.size(); //look at this
while (i < p && j < q)
{
if (j == -1 || haystack[i] == needle[j])
{
i++;
j++;
}
else
j = next[j];
}
if (j == needle.size())
return i - j;
else
return -1;
}
void getNext(std::vector<int>& next, string needle)
{
next[0] = -1;
int i = 0, j = -1;
while (i < needle.size()-1)
{
if (j == -1 || needle[i] == needle[j])
{
++i;
++j;
next[i] = j;
}
else
j = next[j];
}
}
};
对我来说最突出的一件事是你对j和-1的比较,告诉我你期望它在某个时候变成负数(大概是当没有下一个值时(。 假设 j 实际上是负数,您的循环预计会终止。
但它不会。
比较有符号和无符号值有一个令人讨厌的错误,这有令人惊讶的结果。 注意,(-1 <5u(是假的(真的!!(,因为负 int 被提升为 unsigned,而表示为 unsigned 的 -1 是 max unsigned。 因此,循环不会在应该终止的时候终止。
int i = 0, j = 0;
while (i < haystack.size() && j < needle.size()) // BUG: signed/unsigned mixture
{
if (j == -1 || haystack[i] == needle[j])
{
i++;
j++;
}
else
j = next[j];
}
相比之下,当您将大小存储在 int 中时,您正在进行整数比较并且循环正确终止:
int p = haystack.size();
int q = needle.size();
while (i < p && j < q) // *** int to int comparison == good
{
相关文章:
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- while循环中while循环的时间复杂度是多少
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 擦除while循环中迭代的元素
- 为什么我不能在 while 循环中创建线程?
- 退出简单while循环时出现问题
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 嵌套While循环不起作用(C++问题)
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- 使用 GMP 的 while 循环出现问题
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 为什么在 while 循环中返回表达式不起作用
- 如何使用 do while 循环确定最高值和最低值
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 用于在 C++ 中使用 while 循环查找下一个素数的简单函数
- OpenCV QT,显示视频的帧(不使用while循环)
- 输入循环 while 函数
- c++中的循环(while)
- 为什么这段代码没有循环(while)