Leetcode_ZigZag Conversion(c++ version)

来源:互联网 发布:cmd查找mac 编辑:程序博客网 时间:2024/05/22 02:30

地址:http://oj.leetcode.com/problems/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   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".


思路:模拟题。另外一直没有判断nRows <= 1 而一直报MLE。


参考代码:

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


second trial

注意len<=nRows的特殊情况,算出相对位置。可以把第一行和最后一行做特殊处理。

class Solution {public:    string convert(string s, int nRows) {        string ans;        int len = s.length();        if(len<=nRows || nRows==1)            return s;        int j;        for(int i = 0; i<nRows; ++i) {            j = i;            while(j<len) {                ans += s[j];                if(!i || i==nRows-1)                    j += 2*(nRows-1);                else {                    j += 2*(nRows-1)-2*i;                    if(j<len)                        ans += s[j];                    j += 2*i;                }            }        }        return ans;    }};



0 0
原创粉丝点击