LeetCode 6 ZigZag Conversion(规律)
题目来源:https://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 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"
.
解题思路:
Zigzag:即循环对角线结构(
0 | 8 | 16 | |||||||||
1 | 7 | 9 | 15 | 17 | |||||||
2 | 6 | 10 | 14 | 18 | |||||||
3 | 5 | 11 | 13 | 19 | |||||||
4 | 12 | 20 |
)
给出代码:
1 class Solution { 2 public: 3 string convert(string s, int nRows){ 4 if(nRows == 1) return s; 5 string res[nRows]; 6 int i = 0, j, gap = nRows-2; 7 while(i < s.size()){ 8 for(j = 0; i < s.size() && j < nRows; ++j) res[j] += s[i++]; 9 for(j = gap; i < s.size() && j > 0; --j) res[j] += s[i++]; 10 } 11 string str = ""; 12 for(i = 0; i < nRows; ++i) 13 str += res[i]; 14 return str; 15 } 16 };
作者: 伊甸一点
出处: http://www.cnblogs.com/zpfbuaa/
本文版权归作者伊甸一点所有,欢迎转载和商用(须保留此段声明),且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
原文链接 如有问题, 可邮件(zpflyfe@163.com)咨询.