当前位置: 移动技术网 > IT编程>开发语言>C/C++ > #leetcode刷题之路6- Z 字形变换

#leetcode刷题之路6- Z 字形变换

2019年02月28日  | 移动技术网IT编程  | 我要评论

将一个给定字符串根据给定的行数,以从上往下、从左到右进行 z 字形排列。
比如输入字符串为 "leetcodeishiring" 行数为 3 时,排列如下:
l     c     i   r
e t o e s i i g
e    d     h  n
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"lciretoesiigedhn"。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numrows);

示例 1:
输入: s = "leetcodeishiring", numrows = 3
输出: "lciretoesiigedhn"

示例 2:
输入: s = "leetcodeishiring", numrows = 4
输出: "ldreoeiiecihntsg"
解释:

l        d        r
e    o e     i  i
e c     i   h   n
t        s       g

 思路:找规律,怎么找呢?

我们换一种方式来看这道题:

例如:字符串123456789...16和字符串123456789...21

 

规律1:在我圈出的每一列中,同一行之间的相邻数字只差为 len=2*nrows-2,这也就意味着我们知道了第一列每一行的元素,后面的也就全部知道了。

那么问题来了,除了第一行和最后一行,其他行的相邻元素之间会多出现一个字符。。。所以在这些行中,我们要多考虑这些多余的字符。

规律2:这些多余字符的位置也是有规律的,他们和同一行的前一个元素的位置相差len-2*i,也就是说,多余字符的位置为dif=j+len-2*i

ok,按这个规律来做这个题:

#include <iostream>
using namespace std;

string convert(string s, int nrows)
{
    if (nrows <2)
        return s;
    string ans="";
    int len = 2 * nrows - 2;
    for (int i = 0; i < nrows; ++i)
    {
        for (int j = i; j < s.length(); j += len)
        {
            ans += s[j];
            int dif = j +len - 2 * i;
            if ((i != 0) && (i != (nrows - 1)) &&(dif < s.length()))
                ans += s[dif];
        }
    }
    return ans;
}


int main() {
    string s="abcdefghijklmn";
    string ans=convert(s,3);
    std::cout <<ans << std::endl;
    return 0;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网