[LeetCode] [C++] 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 text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
LeetCode 6在线测试

问题描述


第一眼看到这个题目一脸懵逼,什么意思??? 后台百度了下才明白题目意思。就是给定一个字符串
以及int型整数(这个整数用于控制输出几行),以"之"字形的方式输出N行,最后横向来看原来的字符串。
例如:给定字符串"012345678910111213114...",以及输出行数N=5,则之字形输出后的字符串为
之字形输出后样式

思路分析


字符串之字形排序。找出排序规律:一共有N行,则total = 2*(N-1)个字符组成一个完整序列。序列中下标idx % total
如果大于N则下标换为(total-idx) % total ,下标对应在第几行。

例如上文例子中,N=5,则一个序列总共有2*(5-1)=8个数字,从04分别处于不同的四行,57向上排序。

代码验证

class Solution {
public:
    string convert(string s, int numRows) {
        vector<string> vecStrings;
		
		for (int i = 0; i < numRows; ++i) {
		    vecStrings.push_back("");
		}
		
		if (numRows == 1) {
		    return s;
		}
		
		int total = 2*(numRows-1);
		for (int i = 0; i < s.size(); ++i) {
			int idx = i % total;
			if (idx > numRows-1) {
				idx = total - idx;
			}
			vecStrings[idx] += s[i];
		}
		
		string ret;
		for (int i = 0; i < numRows; ++i) {
			ret += vecStrings[i];
		}
		
		return ret;
    }
};

总结注意


之字形转换中,注意每一个字符变换后处于的行数row,也就是idx的计算方式。

原创声明


作者:hgli_00
链接:http://www.cnblogs.com/lihuagang/p/leetcode_6.html
来源:博客园
著作权归作者所有,转载请联系作者获得授权。

posted @ 2017-04-26 20:43  hgli_00  阅读(602)  评论(0编辑  收藏  举报