LeetCode-Z字形变换

将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数:

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

之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR"

实现一个将字符串进行指定行数变换的函数:

string convert(string s, int numRows);

示例 1:

输入: s = "PAYPALISHIRING", numRows = 3
输出: "PAHNAPLSIIGYIR"

示例 2:

输入: s = "PAYPALISHIRING", numRows = 4
输出: "PINALSIGYAHRPI"
解释:

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

P I

class Solution {
	public String convert(String s, int numRows) {

		int length = s.length();
		StringBuffer[] buffer = new StringBuffer[length];
		int index = 0;
		StringBuffer result = new StringBuffer();
		
		for(int i =0;i<length;++i)
		{
			buffer[i]=new StringBuffer();
		}
		
		while (index < length) {
			for (int i = 0; i < numRows&&index<length; ++i) {
				buffer[i].append(s.charAt(index++));
			}

			for (int i = numRows - 2; i > 0&&index<length; --i) {
				buffer[i].append(s.charAt(index++));
			}

		}
		for (StringBuffer tmp : buffer) {
			result.append(tmp);
		}
		return result.toString();
	}
}

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