2016-05-29 24 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

是啊......非常感謝......它幫助! –