【leetcode】6. Z字形变换

6. Z字形变换

《【leetcode】6. Z字形变换》

使用flag代表方向,每次从上至下来回循环,以
行数4为例,索引index的变化情况是0 1 2 3 2 1 0 1 2 3 2… …
每次都将相应行数的数组中增加一个原字符串中的i字符,注意边界判定 

参考资料:https://github.com/richardw0ng/LeetCode/blob/master/docs/Leetcode_Solutions/006._ZigZag_Conversion.md

class Solution {
public:
    string convert(string s, int numRows) {
    	int flag = -1, length = s.length();//flag初始化为-1 
    	int j = 0;
    	string S[numRows];
    	string res;
    	if(numRows == 1 || numRows >= length)//当行数为1或者函数大于字符串长度时,直接按照正常方法排序 
    	    return s;
        for(int i = 0; i < length; i++){
        	S[j] += s[i];//将字符添加到相应位置 
        	if(j == 0 || j == numRows-1)//调转扫描方向 
        	    flag = -flag;
        	j += flag;
		}
		for(int i = 0; i < numRows; i++)//输出结果 
		    res += S[i];
		return res;
    }
};

 

 

 

    原文作者:Z字形编排问题
    原文地址: https://blog.csdn.net/qq_28038873/article/details/82313009
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞