【Leetcode】6.ZigZag Conversion 解题

来源:互联网 发布:大数据与股票预测 编辑:程序博客网 时间:2024/06/15 20:43

【题目描述】:
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   NA P L S I I GY   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 * numRows - 1,当位置处于一个周期的两个端点位置时,一次读取一个字符,否则读取两个字符(同一周期内横着还剩一个)。如第一个周期内,读’A’时,同时读’P’。


【我的代码】:

class Solution {public:    string convert(string s, int numRows) {        //结果字符串        string result = "";        //计算对应numRows的之字形周期        int cycleCount = numRows > 1 ? numRows + (numRows - 2) : 1;        //计算s的长度        int len = (int)s.size();        int index = 0;        //遍历一个周期中的位置偏移量        for (int offset = 0; offset < numRows; ++offset) {            index = offset;            while (index < len) {                result += s.at(index);                //若不为周期的两个端点位置,则再读取一个字符                if (index % cycleCount != 0 && (index - (numRows - 1)) % cycleCount != 0) {                    int off = cycleCount - offset;                    int nextIndex = index - offset + off;                    if (nextIndex < len) {                        result += s.at(nextIndex);                    }                }                index += cycleCount;            }        }        return result;    }};
0 0
原创粉丝点击