【LeetCode】006 ZigZag Conversion

题目:LeetCode 006 ZigZag Conversion

题意:给一个字符串"PAYPALISHIRING" 按照ZigZag的形式,即按照下面的顺序排列,然后

 

在转换成一行一行的读取方式,得到"PAHNAPLSIIGYIR"。其中行数不定。

 

思路:肯定是不能去开一个二维数组的,必须要找出规律来直接输出。发现间隔是和总行数numRows有关,另外,第一行和最后一行需要单独考虑,每两个字符间隔一致,为2*(numRows-1);其余行有两种间隔,设当前为第L行,则第一个间隔为2*(numRows-L),第二个间隔为2*(L-1)。

但是这样我提交后MLE,又是没有考虑特殊情况也是醉了。如果numRows = 1,则单独将第一行和最后一行提出来会出错,只需要返回原字符串即可。

 

代码如下:

class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows == 1) return s;

		string ans = "";
		int len = s.size();
		
		int now = 0;
		while(now < len)
		{
			ans += s[now];
			now += 2*(numRows-1);
		}

		for(int i = 2; i < numRows; i++)
		{
			now = i-1;
			while(now < len)
			{
				ans += s[now];
				now += 2*(numRows-i);
				if(now < len)
				{
					ans += s[now];
					now += 2*(i-1);
				}
				else break;
			}
		}
		now = numRows-1;
		while(now < len)
		{
			ans += s[now];
			now += 2*(numRows-1);
		}
		return ans;
    }
};

  

posted @ 2015-04-29 20:25  二喵de喵  阅读(143)  评论(0)    收藏  举报