ZigZag Conversion - LeetCode 6

来源:互联网 发布:韩顺平java视频有用吗 编辑:程序博客网 时间:2024/05/16 04:14
题目描述:
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  N
A P LS I I G
Y     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".
Hide Tags String

分析:所谓ZigZag Conversion,就是将一个字符串根据指定行数,按照“蛇形”的排列起来,此处的“蛇形”是先竖直方向,然后副对角线方向,从左往右进行。举个栗子:
将序列"0123456789876543210"按5行进行转换后为:
0    8    2  
1  79  31
2 6 8 4 0
35  75
4    6 
那么得到的输出序列则为:"0821793126840357546"

于是可以将转换后的元素按行存起来,然后再拼接起来即可。

以下是C++实现代码:

/*///////////24ms/*/class Solution {public:    string convert(string s, int n) {        if(n == 1)return s;        vector<string> vec(n,""); //存储转换后的每行int len = s.size();int i = 0,j = 0;while(i < len){for(j = 0;j < n && i < len; j++)vec[j].push_back(s[i++]); // 竖直方向,上到下,需要n个字符,依次字符追加到对应行的字符串中for(j = j-2;j > 0 && i < len; j--)vec[j].push_back( s[i++]); //副对角线方向,下到上,一共需要n-2个字符,依次字符追加到对应行的字符串中}string res = "";for(int j = 0; j < n; j++) // 拼接得到结果字符串res.append(vec[j]);return res;    }};


0 0
原创粉丝点击