zoukankan      html  css  js  c++  java
  • ZigZag Conversion leetcode

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

    Subscribe to see which companies asked this question

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

    我们可以将其划分为4个区域

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

    每个区域的数字个数计算公式为:

    cycle = (2 * nRows - 2)

    该例中为 2*nRows - 2 = 4.

    每个区域中, 除了第一行和最后一行,每行都有2个元素

    假设行号是i,则每行的第一个元素下标j为

    j = i + cycle*k, k = 0, 1, 2, ...

    第二个元素下标为:

    secondJ = (j - i) + cycle - i

    (j-i) 是当前区域的第一个, (j-i) + cycle 是下个区域的第一个

    代码如下:

    string convert(string s, int nRows) {
        if (nRows <= 1) return s;
        string result = "";
        //the size of a cycle(period)
        int cycle = 2 * nRows - 2;
        for (int i = 0; i < nRows; ++i)
        {
            for (int j = i; j < s.length(); j = j + cycle) {
                result = result + s[j];
                int secondJ = (j - i) + cycle - i;
                if (i != 0 && i != nRows - 1 && secondJ < s.length())
                    result = result + s[secondJ];
            }
        }
        return result;
    }
  • 相关阅读:
    Application package 'AndroidManifest.xml' must have a minimum of 2 segments.
    让“是男人就下到100层”在Android平台上跑起来
    移植一个cocos2d-x游戏
    cocos2d-x宏定义
    职场之需求
    cocos2d-x for android配置 & 运行 Sample on Linux OS
    input函数出现的问题(Python)
    职场之英语
    职场之随手记
    应用商店后台MIS的一些思考
  • 原文地址:https://www.cnblogs.com/sdlwlxf/p/5103933.html
Copyright © 2011-2022 走看看