LeetCode ZigZag Conversion

链接: https://oj.leetcode.com/problems/zigzag-conversion/


题意为:把字符串按如下规则排列

A     G     M
B   F H   L N
C E   I K   :
D     J     :


输出按行顺序:AGMBFHLNCEIKDJ

剩下的就是通过字符的坐标计算在字符串中的位置了


class Solution
{
	public:
		string convert(string s,int nRows)
		{
			string ans;
			if(s.empty())
			    return ans;
			if(nRows==1)
				return s;
			int n=nRows*2-2;
			int tem=s.length()%n;
			int ncols=(s.length()/n)*2;
			if(tem>=nRows)
				ncols+=2;                           // 计算占的列数
			if(tem<nRows&&tem!=0)
				ncols+=1;
			if(s.length()<=nRows)
				return s;

			for(int i=0;i<nRows;i++)
			{
				for(int j=0;j<ncols;j++)
				{
					if((i==0||i==nRows-1)&&j%2==1)					//短格空白,跳过
						continue;
					if(j%2==1)
					{
						tem=(j-1)/2*n+nRows-1+(nRows-2)-i+1;
						if(tem>=s.length())
							continue;
						ans+=s[tem];
					}
					else
					{
						tem=j/2*n+i;
						if(tem>=s.length())
							continue;
						ans+=s[tem];

					}
				}
			}
			return ans;

		}
};


原文地址:https://www.cnblogs.com/frankM/p/4399433.html