题目描述

The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P A H N
A P L S I I G
Y I R
And then read line by line: “PAHNAPLSIIGYIR”
Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.

思路

字符串先向下然后向右,3就是一竖有3个,对角线也是3个,之后就是循环,因此这是一个找规律的题。

class Solution {
public:
    string convert(string s, int nrow) {
        if(nrow <= 1 || s.length() < 3 || s.length() <= nrow)
        return s;
    string results="";
    int i;
    for(i = 0; i < nrow; i++)
    {
        for(int j = i; j < s.length(); j = j + 2*(nrow - 1))
        {
            results += s[j];
            if(i > 0 && i < nrow - 1)
            {
                if(j+2*(nrow - 1)-2*i < s.length())
                {
                    results+= s[j+2*(nrow - 1)-2*i];    
                }
            }
        }
    }
     return results;
    }
};