【LeetCode】6. ZigZag Conversion

来源:互联网 发布:steam mac dota2 编辑:程序博客网 时间:2024/06/02 03:17

6. ZigZag Conversion

介绍

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

解答

解法十分简单:考虑ZigZag模式的字符,如果有三行 应该是第一行,第二行,第三行,第二行,第一行,第二行····
我们找出每一行,然后直接将每一行的数据相加即可。

class Solution {public:    string convert(string s, int numRows) {       if(numRows == 1) return s;       int len = s.size();       vector<string> rows(numRows);       int row = 0, step = 1;       for(int i = 0; i < len; ++i)       {            rows[row].push_back(s[i]);            if(row == 0)                step = 1;            else if(row == numRows-1)                step = -1;            row = row+step;       }       string res;       for(auto& val:rows)       {           res += val;       }       return res;    }};
原创粉丝点击