6. Z 字形变换

水题

n方即可

class Solution {
public:
    string convert(string s, int numRows) {
        if (numRows == 1) return s;
        int len = s.length();
        int cnt = 0;
        int str[1001][1001];
        memset(str, -1, sizeof(str));
        int j = 0;
        while(cnt < len)
        {
            if(j % (numRows - 1) == 0)
                for(int i = 0; i < numRows && cnt < len; i++)
                    str[i][j] = s[cnt++] - 'a';
            else
            {
                int k = j % (numRows - 1);
                int i = numRows - 1 - k;
                str[i][j] = s[cnt++] - 'a';
            }
            j++;
        }

        string ret = "";

        for(int i = 0; i < numRows; i++)
        {
            for(int k = 0; k < 1000; k++)
                if(str[i][k] != -1)
                {
                    // cout << str[i][k] << endl;
                    ret += 'a' + str[i][k];
                }
        }
        return ret;



    }
};

 

posted @ 2022-03-24 17:32  WTSRUVF  阅读(34)  评论(0编辑  收藏  举报