美文网首页
6. ZigZag Conversion

6. ZigZag Conversion

作者: weego | 来源:发表于2018-04-02 22:37 被阅读0次

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;
}

相关文章

网友评论

      本文标题:6. ZigZag Conversion

      本文链接:https://www.haomeiwen.com/subject/jyrfhftx.html