c++ - Reverse String (Leetcode) 使用 C++,为什么我不能将新字符串作为方法返回

标签 c++ arrays pointers

问题:编写一个函数,将字符串作为输入并返回反转的字符串。

示例:给定 s = "hello",返回 "olleh"。

这段代码有什么问题?

class Solution {
public:
    string reverseString(string s) {

        string s2;

        for(int i=0; i<s.length(); i++)
            s2[i] = s[s.length()-1-i];

        return s2;
    }
};

最佳答案

您超出了绑定(bind)访问权限,您必须在分配之前调整结果字符串的大小。

std::string reverseString(const std::string& s) {
    std::string s2(s.size(), '\0');

    for(int i=0; i<s.length(); i++)
        s2[i] = s[s.length()-1-i];

    return s2;
}

或者简单地使用正确的构造函数:

std::string reverseString(const std::string& s) {
    return {s.rbegin(), s.rend()};
}

关于c++ - Reverse String (Leetcode) 使用 C++,为什么我不能将新字符串作为方法返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38947853/

相关文章:

C++ 字符串到 bool 数组

c - 使用 C 中的 YAJL 树检测 JSON 文件中的数组时出现问题

ruby - 计算数组中连续整数元素的数量

c++ - 向双端队列指针发出设置值

c - 将指针传递给具有 volatile 成员的结构作为函数参数

C++ iostream 运算符覆盖函数返回类型

c++ - penter 和 pexit 的 Visual Studio 宏

c++ - 需要一些解密 opencv 线角度

arrays - 如何打乱一组 UIViews

C++:在 cin.getline() 中使用指针