c++ - 在 ‘n’ 行中打印 Zig-Zag 字符串的串联

标签 c++ string vector

I have been given a string and number of rows n. Print the string formed by concatenating n rows when input string is written in row-wise Zig-Zag fashion

std::string str = convert("PAYPALISHIRING", 3); //str == "PAHNAPLSIIGYIR"

这是一个视觉图像

P.......A........H.......N
..A..P....L....S....I...I....G
....Y.........I........R

我写了下面的代码

string Solution::convert(string A, int B) {//B is no of rows in zigzag pattern
    if(B==1)
        return A;
    int n=B;
    vector<string> vec;
    int dir=0;//0 means down, 1 means up
    int row=0;
    for(int i=0;i<A.length();i++)
    {
        vec[row].append(A,i,1);
        if(row==n-1)
            dir=1;//change to upwards
        if(row==0)
            dir=0;//change to downwards

        if(dir==0) row++;
        else row--;
    }
    string ans="";
    for(int i=0;i<B;i++)
        ans.append(vec[i]);

    return ans;
}

但是对于所有 B >= 2 它给出了一个段错误。

有什么想法吗?

最佳答案

这一行 vec[row].append(A,i,1);

您正在访问索引 row 处的字符串,但是 vec 是空的!你不能那样做,所以你会遇到段错误!

您需要指定 vector 的大小:

//'vec' will never have more than 'B' elements
std::vector<std::string> vec(B);

关于c++ - 在 ‘n’ 行中打印 Zig-Zag 字符串的串联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37511177/

相关文章:

c++ - C++中从树中删除节点的算法

c++ - 使用 Swift 或 Objective-C 创建 Dylib 文件

c++ - 有效地填充已知大小的 vector

c++ - 在 GCC 中链接 .h 文件

python - 将 python 字典转换为逗号分隔键字符串和逗号分隔值字符串的优雅方法是什么?

python/objective-c utf8 比较不同

java - 字符串的插入排序

image-processing - 向矢量添加噪声

c++ - 将空间重新分配到 vector::resize() 以降低计数时?

c++ - 3D C++ 任意网格三角剖分库?