LeetCode(6) - ZigZag Conversion

来源:互联网 发布:虚荣 知乎 编辑:程序博客网 时间:2024/03/29 16:47

题目描述:

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-2,其他循环周期为2*numRows-2-2*i。

方法一:

class Solution {public:    string convert(string s, int numRows) {        int len = s.length();        string ret;                if(len == 0 || numRows < 2) return s;                int lag = 2*numRows-2;        for(int i = 0; i < numRows; i++){            for(int j = i; j < len; j += lag){                ret += s[j];                                if( i > 0 && i < numRows-1){                    int t = j + lag - 2*i;                    if( t < len) ret += s[t];                }            }                    }        return ret;    }};


0 0
原创粉丝点击