首页 > 解决方案 > 返回空值的字符串值

问题描述

在我的代码中,当我尝试在函数 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 " ";
    }
}

标签: c++oop

解决方案


您不能使用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)

推荐阅读