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:
- P.......A........H.......N
- ..A..P....L..S....I...I....G
- ....Y.........I........R
Therefore, <ABCD, 2> can be arranged as:
- A....C
- ...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
- LeetCode 6 - ZigZag Conversion
- LeetCode 6: ZigZag Conversion
- LeetCode(6)ZigZag Conversion
- Leetcode【6】:ZigZag Conversion
- [leetcode 6] ZigZag Conversion
- LeetCode 6 ZigZag Conversion
- LeetCode(6) ZigZag Conversion
- [Leetcode] 6 - ZigZag Conversion
- LeetCode 6:《ZigZag Conversion》
- [leetcode 6] ZigZag Conversion
- LeetCode | #6 ZigZag Conversion
- [leetcode] 6 ZigZag Conversion
- leetCode #6 ZigZag Conversion
- leetcode 6 ZigZag Conversion
- leetcode-6 ZigZag Conversion
- leetcode 6 ZigZag Conversion
- LeetCode 6 - ZigZag Conversion
- leetcode 6ZigZag Conversion
- 能力成长模型
- 小技巧:Parallels Desktop 的中统一mac和Linux 虚拟机的拷贝粘贴为 cmd+c cmd+v
- 蓝桥杯历届试题之振兴中华
- 输入一个整数,然后逆序输出
- from c to c++: using the boolean
- leetcode-6 ZigZag Conversion
- 二叉排序树
- 怎么增加新浪微博阅读量
- Archlinux中IO占用高而不退
- java基础复习之面向对象语法基础
- sql server dbnetlib 不存在或者拒绝服务解决方案
- JavaScript中判断日期是否相等
- 态度
- 学习实现马赫带效果