6. ZigZag Conversion

2018-04-02  本文已影响0人  weego

Description

The string "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 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)

And then read line by line:"AIQYBHJPRXZCGKOSWDFLNTVEMU"
Write the code that will take a string and make this conversion given a number of rows:


zigzag.png

string convert(string text, int nRows);
convert("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 5) should return "AIQYBHJPRXZCGKOSWDFLNTVEMU".

Solution

细节题目,遍历s,将字符s[i] append到对应字符串中即可,最终遍历字符串数组求解

string convert(string s, int numRows) {
    if (numRows == 1 || s.length() <= 1) {
        return s;
    }
    int rowSize = 2 * numRows - 2;
    string strConverted = "";
    vector<string> strRows(numRows, "");
    for (int i = 0; i < s.length(); ++i) {
        int remain = i%(rowSize);
        remain = (remain<numRows? remain : rowSize-remain);//如果是斜边,需要重新计算index
        strRows[remain] = strRows[remain] + s[i];
    }
    for (int j = 0; j < numRows; ++j) {
        strConverted += strRows[j];
    }
    return strConverted;
}
上一篇 下一篇

猜你喜欢

热点阅读