LeetCode---(6)ZigZag Conversion

来源:互联网 发布:如何写bat文件运行java 编辑:程序博客网 时间:2024/04/28 19:09

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   NA P L S I I GY   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个公式:
1 之字形行数为nRows,那么每次重复样出现前的间隔字符为zigSpan = nRows*2-2;
2 第一行和最尾一行都是存放一个字符的,所以存储的字符为间隔为zigSpan的字符
3 中间行是需要额外存储多一个字符的,存储的字符位置是: zigSpan + j - 2*i
class Solution {public:    string convert(string s, int numRows) {        if(numRows<=1||s.size()==0)            return s;        string res;        int zigSpan = numRows*2-2;        for(int i=0;i<numRows;i++)        {            for(int j=i;j<s.size();j+=zigSpan)            {                res.push_back(s[j]);                if(i!=0&&i!=numRows-1&&zigSpan+j-2*i<s.size())                    res.push_back(s[zigSpan+j-2*i]);            }        }        return res;    }};



0 0