leetcode-6 ZigZag Conversion

来源:互联网 发布:java数据源配置 编辑:程序博客网 时间:2024/04/29 22:41

题解

 这道题就是看坐标的变化。并且需要分块处理。

 n=2时,字符串坐标变成zigzag的走法就是:

 0 2 4 6

 1 3 5 7

 n=3时的走法是:

 0     4     8

 1  3 5  7 9

 2     6    10 

 n=4时的走法是:

 0      6        12

 1   5 7    11 13

 2 4   8 10    14

 3      9         15 

 

 可以发现规律,画红色的长度永远是 2n-2 (想法是你试想把所有这些行压缩成两列,两边手挤一下,第二列永远的第一行和最后一行少字)。

 利用这个规律,可以按行填字,第一行和最后一行,就是按照2n-2的顺序一点点加的。

 其他行除了上面那个填字规则,就是还要处理斜着那条线的字,可以发现那条线的字的位置永远是当前列j+(2n-2)-2i(i是行的index)。 

 按照上面的规律就可以写出代码了。

<span style="font-family:Microsoft YaHei;font-size:14px;"><span style="font-family:Microsoft YaHei;font-size:14px;">char *convert(char *s, int nRows) {   if(s == NULL ||  nRows < 1) return NULL;      int len = strlen(s);   char *res = malloc(sizeof(char) * (len + 1));   res[len] = '\0';      if(nRows == 1){       return strcpy(res,s); //<span style="line-height: 26px;">C语言代码 注意就算s只有一行,也不能return s; 要malloc 内存 strcpy 再返回。</span>   }      int index = 0;   int i,j;   int size = 2 * nRows - 2;   for(i = 0; i < nRows; i++){       for(j = i; j < len; j += size){           res[index++] = s[j];           if(i != 0 && i != nRows -1){               int tmp = j + size - 2 * i;               if(tmp < len)                   res[index++] = s[tmp];           }       }   }      return res;}</span></span>

另外一种很好的思路:

The problem statement itself is unclear for many. Especially for 2-row case. "ABCD", 2 --> "ACBD". The confusion most likely is from the character placement. I would like to extend it a little bit to make ZigZag easy understood.

The example can be written as follow:

  1. P.......A........H.......N
  2. ..A..P....L..S....I...I....G
  3. ....Y.........I........R

Therefore, <ABCD, 2> can be arranged as:

  1. A....C
  2. ...B....D

My simple accepted code:

<span style="font-family:Microsoft YaHei;font-size:14px;">class Solution {public:    string convert(string s, int nRows) {        if(s == "" || nRows <= 1) return s;                int step = 1;        int row = 0;        string *str = new string[nRows];                for(int i = 0; i < s.size(); i++){            str[row].push_back(s[i]);                        if(row == 0)                step = 1;            else if(row == nRows -1)                step = -1;                            row += step;        }        s.clear();        for(int j = 0; j < nRows; j++){            s.append(str[j]);        }        delete [] str;        return s;    }};</span>


转自:http://www.cnblogs.com/springfor/p/3889414.html

参考:https://leetcode.com/discuss/14483/share-simple-c-solution

0 0
原创粉丝点击