• 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 - 2 - 2 * i

    C++代码如下:

    #include<iostream>
    #include<string>
    using namespace std;
    
    class Solution {
    public:
            string convert(string s, int nRows) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            string result;
            if (nRows < 2) return s;
            for (int i = 0;i < nRows;++i) {
                for (int j = i;j < s.length();j += 2 * (nRows - 1)) {
                    result.push_back(s[j]);
                    if (i > 0 && i < nRows - 1) {
                        if (j + 2 * (nRows - i - 1) < s.length())
                            result.push_back(s[j + 2 * (nRows - i - 1)]);
                    }
                }
            }
            return result;
        }
    };
    
    int main()
    {
        Solution s;
        string ss="PAYPALISHIRING";
        string sss="0123456789";
        cout<<s.convert(sss,4)<<endl;
    }

    运行结果:

  • 相关阅读:
    安装thrift时,注意openssl参数
    Linux下boost编译安装
    super-smack
    算术运算指令
    C/C++中有关字长与平台无关的整数类型
    URLTester2.3.2
    第20课 链接过程简介
    第19课 编译过程简介
    第18课 三目运算符和逗号表达式
    第17课 ++和--操作符分析
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4099368.html
Copyright © 2020-2023  润新知