【发布时间】:2021-11-07 02:55:03
【问题描述】:
minlen 变量仅在 middle cout 中打印,并在其他任何地方使用时给出随机值
class Solution
{
public:
string longestCommonPrefix(vector<string>& strs)
{
int sofar = sizeof(strs) / 8;
int len[sofar], i, j, minlen;
string newstr = "";
for(i = 0; i < sofar; i++)
{
len[i] = strs[i].length();
if(len[i] < minlen)
minlen = len[i];
}
//!!!!!!!!!!!!!!!!!!! HERE !!!!!!!!!!!!!!!!!!!!
cout << minlen << endl;
cout << "sofar : " << sofar << endl << "minlen : " << minlen << endl;
cout << minlen << endl;
/*for(i=0;i<mlen;i++)
{
cout<<"outer"<<endl;
for(j=0;j<sofar-1;j++)
{
cout<<"middle"<<endl;
if(strs[j][i]==strs[j+1][i])
{ newstr=newstr+strs[j+1];
cout<<"innermost"<<endl;
}
}
}*/
return newstr;
}
};
【问题讨论】:
-
你没有初始化
minlen,所以if(len[i]<minlen)是未定义的行为 -
另外
sizeof(strs) / 8绝对不是你想要的(为什么 / 8 无论如何?)。你想要strs.size() -
将 sizeof(strs) / 8 更改为 strs.size() 修复了它
-
@madlading 如果您对答案感到满意,请点击其左侧的复选框接受。
标签: c++ string vector string-length