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

 

 

Subscribe to see which companies asked this question

 

题意挺难懂吧。就是把字符串Z型实现,而且不是ZZ这样,就是纵项和斜项交叉显示。

刚开始打算直接用string实现,然后寻找下标的关系,但是发现有可能有多个Z

后来发现我们只需要逐个打印每行,这样用map实现不是很好嘛~!

 

所以计算下标的规律就好了。

 

 1 class Solution {
 2 public:
 3 
 4     string convert(string s, int numRows) {
 5         string result="";
 6         int len=s.length();
 7         if(numRows>=len||numRows==1) return s;
 8         int c=numRows-2;     //斜项的个数
 9         int g=c+numRows;     //一个z需要的个数(因为不是ZZ而是纵项斜项交叉的,所以不是2*numRows+c)
10         int index=0;
11         map<int,string> mp;
12         for(int i=0;i<len;i++){
13             index=i%g;
14             if(0<=index&&index<=numRows-1) mp[index]+=s[i];
15             if(numRows<=index&&index<=numRows+c-1) mp[numRows+c-index]+=s[i];
16         }
17         for(auto i=mp.begin();i!=mp.end();i++){
18             result+=(*i).second;       
19         }
20         return result;
21     }
22 };

 

 

posted @ 2015-12-28 09:42  0giant  阅读(251)  评论(0编辑  收藏  举报