leetcode(6)-ZigZag Conversion
来源:互联网 发布:苹果手机免费赚钱软件 编辑:程序博客网 时间:2024/04/28 03:07
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 RAnd 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"
.
思想是: 每numRows+1个元素为一组,计算一共多少组,每一组中的最后一个元素就是中间出现的元素。画个图可以看出来,可以计算出各个元素的坐标,相当于把二维数组拉成一维的样子 ---。---。---。---。-- 如上面的把字串分成5组。 注意的问题: 1.可能元素总个数少于numRows+1 或者 只分一行,只有一个元素,可直接返回class Solution {public:string convert(string s, int numRows) {if (1 == numRows || s.size() == 1)return s;int index=0;int N;//the group counts ,each group has (numRows+1) members.int strLen = s.size();string retStr(strLen + 1, '\0');int mid;//middle rowsif (numRows%2)//odd rowsmid = numRows / 2;elsemid = numRows / 2 -1;N = strLen / (numRows+1);// N may be zero when the size of the string <= numRows if (!N)return s;if (strLen % N)N += 1;for (int j = 0; j < numRows; ++j)//j is the offset in the group{for (int i = 0; i < N; ++i)//i is the offset of the group{int m = i * (numRows+1) + j;if (m < strLen){retStr[index++] = s[m];if (j == mid){int mm = i * (numRows + 1) + numRows;if (mm < strLen)retStr[index++] = s[mm];}}}}return retStr;}};
0 0
- 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
- map-reduce入门
- android ListActivity详解
- WebView loadurl导致的空指针问题
- RabbitMQ (五)主题(Topic)
- Android wiki:12.GestureDetector屏幕手势
- leetcode(6)-ZigZag Conversion
- Repeated DNA Sequences -- leetcode
- Android wiki:13.开机启动广播接收者
- RabbitMQ (六)远程调用RPC
- Android wiki:14.修改Toast样式
- PHP之LAMP环境配置与优化
- 【8.17】建立一个用来实现求3个数和的类模板(将成员函数定义在类模板的内部),并写出调用此类模板的完整程序。
- Android wiki:14.自定义Toast样式
- iOS开发之使用代码定位性更高的Log