码迷,mamicode.com
首页 > 其他好文 > 详细

6. ZigZag Conversion

时间:2017-12-31 18:44:55      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:this   pre   splay   int   nbsp   convert   char   思路   and   

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".

思路:z字型填一个矩阵,时间复杂度为O(n^2),注意边界值

 1 class Solution {
 2 public:
 3     string convert(string s, int numRows) {
 4         if(s.size()==0 || s.size()<=numRows || numRows<=1)return s;//注意边界值
 5         int numCols=s.size()*2/(numRows*2-2)+1;
 6         char **arr=(char**)malloc(sizeof(char*)*numRows);
 7         for(int i=0; i<numRows; ++i)//初始化矩阵
 8         {
 9             arr[i]=(char*)malloc(sizeof(char)*numCols);
10             for(int j=0; j<numCols; ++j)arr[i][j]=\0;
11         }
12         int k=0;
13         for(int j=0; j<numCols; j=j+2)//填矩阵
14         {
15             for(int i=0; i<numRows && k<s.size(); ++i)arr[i][j]=s[k++];
16             if(j+1<numCols)
17             {
18                 for(int i=numRows-2; i>=1 && k<s.size(); --i)arr[i][j+1]=s[k++];
19             }
20         }
21         string str;
22         for(int i=0; i<numRows; ++i)//遍历矩阵得到结果
23         {
24             for(int j=0; j<numCols; ++j)
25             {
26                 if(arr[i][j]!=\0)str=str+arr[i][j];
27             }
28         }
29         for(int i=0; i<numRows; ++i)delete []arr[i];//释放内存
30         delete []arr;
31         return str;
32     }
33 };

 

6. ZigZag Conversion

标签:this   pre   splay   int   nbsp   convert   char   思路   and   

原文地址:https://www.cnblogs.com/jeysin/p/8157979.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!