2016-05-29 23 views
0

我给出了字符串和行数n。打印通过连接n行形成的字符串时,输入字符串写入逐行的之字形的方式在'n'行中打印Z字形串连接

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它给出了分段错误。

任何想法?

回答

1

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

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

你需要指定向量的大小:

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

是啊......非常感谢......它帮助! –