Fork me on GitHub

Leetcode6.ZigZag ConversionZ字形变换

将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数:

之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR"

实现一个将字符串进行指定行数变换的函数:

string convert(string s, int numRows);

示例 1:

输入: s = "PAYPALISHIRING", numRows = 3 输出: "PAHNAPLSIIGYIR"

示例 2:

输入: s = "PAYPALISHIRING", numRows = 4 输出: "PINALSIGYAHRPI"

解释:

 

class Solution {
public:
    string convert(string s, int numRows)
    {
        int len = s.size();
        if(len == 0)
            return "";
        if(numRows == 1)
            return s;
        vector<vector<char> > v(len, vector<char>(len, 0));
        int i = 0, j = 0;
        int cnt = 0;
        while(cnt < len)
        {
            if(j % (numRows - 1) == 0)
            {
                for(i = 0; i < numRows && cnt < len; i++)
                {
                    v[i][j] = s[cnt++];
                }
                j++;
                i--;
            }
            else
            {
                v[--i][j++] = s[cnt++];
            }
        }
        string res = "";
        for(int i = 0; i < len; i++)
        {
            for(int j = 0; j < len; j++)
            {
                if(v[i][j] != 0)
                    res += v[i][j];
            }
        }
        return res;
    }
};

posted @ 2018-11-17 18:53  lMonster81  阅读(76)  评论(0编辑  收藏  举报
/*评论*/ /*top按钮*/

/* 网易云控件 */