导航

LeetCode 6. ZigZag Conversion

Posted on 2016-09-20 21:15  CSU蛋李  阅读(141)  评论(0编辑  收藏  举报

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".

这个题目只要找到每一行字符串间隔的规律就行了,第一行和最后一行间隔 2 * (numRows - 1),中间行每次插入两个他们之间间隔2 * (numRows-i)

 

class Solution {
public:
    string convert(string s, int numRows) {
        if (numRows <= 1)return s;
        string ret;
        for (int i = 1;i <= numRows;++i)
        {
            for (int j = i-1;j < s.size();j += 2 * (numRows - 1))
            {
                if (1 == i || numRows == i)
                {
                    ret.push_back(s[j]);
                }
                else
                {
                    ret.push_back(s[j]);
                    if(j+2 * (numRows-i)<s.size())
                    ret.push_back(s[j + 2 * (numRows-i)]);
                    else break;
                }
            }
        }
        return ret;
    }
};