6. ZigZag Conversion

来源:互联网 发布:php 清空文件 编辑:程序博客网 时间:2024/05/16 15:31

1 ,思路

首先生成一个二维矩阵,然后按照规则,也就是先从上到下,然后斜向上。
然后遍历完字符串之后,将其按照先行后列读出即可。

2 代码

class Solution {public:    string convert(string s, int numRows) {        int n = s.size();        if(numRows == 1){            return s;        }        int t = numRows*2 - 2;        int col =  ceil(n*1.0/t) * (numRows-1);        char map_t[numRows][col] = {0} ;        for(int i = 0; i < numRows; i++){            for(int j = 0; j < col; j++){                map_t[i][j] = 0;            }        }        int i = 0;        int rx = 0;        int rj = 0;        while(i < n){            while(i < n && rx < numRows){                map_t[rx][rj] = s[i];                rx++;                i++;            }            //斜向上            rx = rx -2;            rj ++;            while(i < n && rx > 0){                map_t[rx][rj] = s[i];                rx--;                rj++;                i++;            }        }        string res = "";        for(int i = 0;i < numRows; i++){            for(int j = 0; j < col; j++){                if(map_t[i][j] != 0){                    res += map_t[i][j];                }            }        }        return res;    }};
0 0
原创粉丝点击