(字符串)ZigZag Conversion

【解析】

第一次看到这个题目的人,可能不知道ZigZag是什么意思,简单解释一下,就是把字符串原顺序012345……按下图所示排列:

发现所有行的重复周期都是 2 * nRows - 2

对于首行和末行之间的行,还会额外重复一次,重复的这一次距离本周期起始字符的距离是 2 * nRows - 2 - 2 * i


    1. class Solution {  
    2. public:  
    3.     string convert(string s, int nRows) {  
    4.         // Start typing your C/C++ solution below  
    5.         // DO NOT write int main() function  
    6.         string result;  
    7.         if (nRows < 2) return s;  
    8.         for (int i = 0;i < nRows;++i) {  
    9.             for (int j = i;j < s.length();j += 2 * (nRows - 1)) {  
    10.                 result.push_back(s[j]);  
    11.                 if (i > 0 && i < nRows - 1) {  
    12.                     if (j + 2 * (nRows - i - 1) < s.length())  
    13.                         result.push_back(s[j + 2 * (nRows - i - 1)]);  
    14.                 }  
    15.             }  
    16.         }  
    17.         return result;  
    18.     }  
    19. }; 
原文地址:https://www.cnblogs.com/Kobe10/p/6364220.html