LeetCode 6. ZigZag Conversion

来源:互联网 发布:数据可视化工具 编辑:程序博客网 时间:2024/05/19 00:11

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

先按照要求的顺序排好字母,然后遍历输出即可。

class Solution {public:    string convert(string s, int numRows) {char c[1000][1000];        int i = 0, j = 0;        if(numRows == 1) return s;        int len = s.size();        int count = 0;        bool down = true;        int length;        string res = "";        for(i = 0; i < numRows; i ++){    for(j = 0; j < 1000;  j ++){c[i][j] = ' ';    }}i = 0; j = 0;        while(count < len){            if(down){                if(i < numRows){                    c[i ++][j] = s[count ++];                 }else{                    down = false;                    j ++;                    i -= 2;                }            }else{                if(i > -1){                    c[i --][j ++] = s[count ++];                   }else{                    down = true;                    i += 2;                    j --;                }            }        }          length = j;        for(i = 0; i < numRows; i ++){        for(j = 0; j <= length; j ++){        if(c[i][j] != ' ') res += c[i][j];        }         }    return res;    }};


0 0
原创粉丝点击