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   N
A P L S I I G
Y   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 = 3,字母排列如下:

  P          A

  A    P    L

  Y          I           (按Z字形排列)

  nRows = 4,字母排列如下:

  P               I

  A         L    S

  Y    A         H 

  P               I      (按Z字形排列)

  


  代码很简单,自己写了一个

solution1:

string convert(string s, int nRows) {
    int len = s.size();
    if(len <= 2 || nRows <=1)
        return s;
    if(len <= nRows)
        return s;
    vector<string> res(nRows);
    int num = 2 * (nRows-1);
    int *loop = new int[num];
    int i,j;
    for (i = 0;i < nRows;++i)
    {
        loop[i] = i;
    }
    for (j = nRows-2;j > 0;--j)
    {
        loop[i++] = j;
    }
    int count = len / num;
    i = 0;
    for (j = 0;j < count;++j)
    {
        for (int k = 0;k < num;++k)
        {
            res[loop[k]] += s[i++];
        }
    }
    int k = 0;
    for (;i < len;++i)
    {
        res[loop[k++]] += s[i];
    }
    for (i = 1;i < nRows;++i)
    {
        res[0] += res[i];
    }
    delete [] loop;
    return res[0];
}

  看上去太过粗糙,下面的更精简
solution2:

string convert(string s, int nRows) {
    if(nRows < 2)
        return s;
    int len = s.size();
    vector<string> res(nRows);
    int i = 0;
    while (i < len)
    {
        for (int idx = 0;idx < nRows && i < len;idx++)   // vertically down
            res[idx] += s[i++];
        for (int idx = nRows-2;idx >=1 && i < len;idx--) // obliquely up
            res[idx] += s[i++];
    }
    for (int idx = 1;idx < nRows;idx++)
        res[0] += res[idx];
    return res[0];
}

来源:https://oj.leetcode.com/discuss/10493/easy-to-understand-java-solution

  

posted @ 2014-12-19 19:54  Sawyer Ford  阅读(190)  评论(0编辑  收藏  举报