zoukankan      html  css  js  c++  java
  • [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".

    程序很简单第一排和最后一排是一组公式,2*nRows-2,,其他排用另一组公式,分奇偶,公式分别是2 * (nRows - i - 1)和2 * i 。时间:29ms

    代码如下:

    class Solution {
    public:
        string convert(string s, int nRows) {
            if (nRows <= 1 || s.size() == 0)
                return s;
            string str;
            for (int i = 0; i < s.size() && i < nRows; i++){
                int j = i, x=1;
                while (j < s.size()){
                    str += s[j];
                    if (i == 0 || i == nRows-1)
                        j += 2 * nRows - 2;
                    else{
                        if (x & 0x1)
                            j += 2 * (nRows - i - 1);
                        else
                            j += 2 * i;
                        x++;
                    }
                }
            }
            return str;
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    C++解决单纯形表
    VS2010 MFC Excel(3)
    VS2010 MFC Excel(1)
    VS2010 MFC 读取Excel(2)
    读取数量不定的输入数据
    牛顿插值
    连接数据库
    雅克比迭代
    NOIP模拟 24
    NOIP模拟 23
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4401941.html
Copyright © 2011-2022 走看看