其他分享
首页 > 其他分享> > 6. ZigZag Conversion

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 N
A P L S 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 s, int numRows);
Example 1:

Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Example 2:

Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:

P I N
A L S I G
Y A H R
P I

题意:
给一个字符串,先把它按照一列从上到下排,然后斜着向上,等到了底端再一列从上往下。
再把这种排列的每一行拼接起来。
方法:
直接模拟这个过程就完整了。

class Solution {
public:
	string convert(string s, int numRows) {
		int l = s.length();
		string rst;
		int* rows = (int*)malloc(sizeof(int) * l);
		int row = 0;
		int direction = 1;
		memset(rows, 0, sizeof(int) * l);
		for (int i = 0; i < l; i++)
		{
			rows[i] = row;
			if ((row+direction) >= numRows)
			{
				direction = -1;
			}
			else if ((row + direction) < 0)
			{
				direction = 1;
			}
			if (numRows == 1) direction = 0;
			row += direction;
		}
		for (int i = 0; i < numRows; i++)
		{
			for (int j = 0; j < l; j++)
			{
				if(rows[j]==i)
				rst.append(1, s[j]);
			}
		}
		free(rows);
		return rst;
	}
};

结果:
Runtime: 48 ms, faster than 12.06% of C++ online submissions for ZigZag Conversion.
Memory Usage: 11 MB, less than 53.70% of C++ online submissions for ZigZag Conversion.

标签:Conversion,rows,string,int,direction,ZigZag,numRows,row
来源: https://blog.csdn.net/jmh1996/article/details/100080525