I have been given a string and number of rows
n
. Print the string formed by concatenatingn
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/