gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:39:21 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com