LeetCode 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" .

分析:
    题意:ZigZag的中文含义是锯齿形的,之字形的, Z字形的”,顾名思义,这道题是给定一个字符串,按照Z字形排列,返回它的按行读取字符组成的字符串。
    思路:这是一道找规律的数学题,我们发现,当设为nRows行时,第一行和最后一行,水平相邻字符之间的距离step = 2 * nRows - 2,中间第i行(0, 1, 2, ..., nRows - 1)水平间距为step' = step - 2 * i。

LeetCode 6

    注意一点:当nRows=1时,刚好排成一条水平线;当nRows大于等于字符串长度时,刚好排成一条竖直线,这两种情况可以特殊考虑。假设字符串的长度为n,则时间复杂度为O(n * nRows))

代码:

#include <bits/stdc++.h>

using namespace std;

class Solution {
public:
    string convert(string s, int numRows) {
        int n = s.length();
		// Exceptional Case: 
		if(n == 0 || numRows == 1 || n <= numRows){
			return s;
		}
		string ans, tmp = "#";
		int step = 2 * numRows - 2;
		for(int i = 0; i <= numRows - 1; i++){
			int j = i;
			if(i == 0 || i == (numRows - 1)){
				while(j <= n - 1){
					tmp[0] = s[j];
					ans += tmp;
					j += step;
				}
			}
			else{
				int ss = step - i * 2;
				while(j <= n - 1){
					tmp[0] = s[j];
					ans += tmp;
					j += ss;
					ss = step - ss;
				}
			}
		}
		return ans;
    }
};



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值