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

leetcode - ZigZag Conversion

时间:2015-06-12 18:55:55      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

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

 1 class Solution {
 2 public:
 3     string convert(string s, int numRows) {
 4         vector<string> result(numRows);
 5         bool increase = true;
 6         string output;
 7         string::iterator iter = s.begin();
 8         int i = 0;
 9         if(s.size()<numRows || numRows == 1){ //special cases
10             return s;
11         }
12         result[0].push_back(*iter);// the first character
13         iter++;
14         while(iter != s.end()){
15             if(increase){
16                 i++;
17             }
18             else{
19                 i--;
20             }
21             if(i==(numRows-1) || i==0){ //here, avoid that i=0 for the first charater, it will become false.(it should be ture) 
22                 increase = !increase;
23             }
24             result[i].push_back(*iter);
25             iter++;
26         }
27         for(int j=0; j<numRows; j++){
28             output += result[j];
29         }
30         return output;
31     }
32 };

思路: 建立numRows维vector存放每行数据,然后开始遍历,i控制行号,行号从0-(numRow-1),再到0,一直循环。

直到全部字符遍历完,按行输出即可。

要注意特殊情况,行数大于字符总数,或者行数等于一(好像已经考虑过了。。)。

leetcode - ZigZag Conversion

标签:

原文地址:http://www.cnblogs.com/shnj/p/4572025.html

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