(1) 對於第一行與最後一行,每兩個相鄰元素在原字符串中的距離爲2*(nRows-1);c++
(2) 對於非第一行與最後一行的其餘行curRow,若鋸齒(zigzag)正往下走。則當前字符與下一個字符在原字符中的距離爲2*(nRows-curRow-1);若鋸齒正往上走,則當前字符與下一個字符在原字符中的距離爲2*curRow。post
string convertex(string s ,int numRows) { int size = s.size(); if (size <= numRows || numRows <= 1) return s; string res(size, '0'); int c = 0; int tempRow = (numRows - 1) * 2; //first row for (int i = 0; i < size; i += tempRow) { res[c++] = s[i]; } //middle for (int curRow = 1; curRow < numRows - 1; ++curRow) { for (int j = curRow; j < size; j += 2 * curRow) { res[c++] = s[j]; j += (numRows - curRow - 1) * 2; if (j < size) { res[c++] = s[j]; } } } //the last row for (int i = numRows - 1; i < size; i += tempRow) { res[c++] = s[i]; } return res; }