c++ - 返回空值的字符串值
问题描述
在我的代码中,当我尝试在函数 str 中打印结果的值时,它一直显示为 null。可以请一些输入。它显示正确的值当我尝试在每次迭代的 for 循环中显示结果的值时。
string str(string s, int mid){
string result;
for(int j=0;j<=mid;j++){
result[j]= s[j];
}
return result;
}
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int min= 0, max= 0,mid = 0;
string temp2;
max = strs[0].length()-1;
mid = (min + max)/2;
string temp = str(strs[0],mid);
int flag1 = 0,flag2 = 1;
cout<<temp<<endl;
while(1){
for(int i=1;i<strs.size(); i++){
if(strs[i].compare(0,mid+1,temp,0,mid+1)!=0){
if(flag1 == 1)
return temp2;
if(mid == 0)
return " ";
max = mid;
temp2 = temp;
mid = (min + max)/2;
cout<<temp<<endl;
temp = str(strs[0],mid);
i = 1;
}
if(i+1 == strs.size()){
if(mid == max)
return temp;
min = mid;
temp2 = temp;
mid = (min + max)/2;
temp = str(strs[0],mid);
i = 1;
flag1 = 1;
}
}
return " ";
}
}
解决方案
您不能使用operator[]
. 您的书写越界并导致未定义的行为。采用
result += s[j];
添加字符或用正确的大小初始化字符串
string result(mid, '\0');
或者简单地复制字符串;
auto result = s.substr(0, mid + 1);
您可以将功能替换str
为
string str(string s, int mid){
return s.substr(0, mid + 1);
}
甚至删除该功能并替换每个调用
str(strs[0],mid)
通过调用
strs[0].substr(0, mid + 1)
推荐阅读
- swift - 将 UILabel 设置为粗体?
- python - Pyinstaller 生成不执行任何操作的 EXE
- c# - 为什么视图无法在客户端显示学生数据并且它是 ASP.NET MVC?
- java - 列表
- > 到二维数组的转换 (int[][])
- angular - 茉莉模拟值和服务值不同
- java - 在输入的情况下创建不同的装饰对象
- java - 尝试打开某些活动时,Android 应用程序关闭
- telegram-bot - 与机器人聊天时的自定义键盘
- ios13 - 在 iOS 13 中使用 NDI SDK 4.5 的视频广播不起作用。局域网接收器收不到任何视频包
- ios - 使用单个按钮 Xcode 或 swift 切换视图控制器的背景颜色