No.6 ZigZag Conversion

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

注意:其实思路想到了,但不敢相信自己的想法,没有坚持下去,加油!

方法一:时间复杂度O(n),空间复杂度O(1)

 

 1 class Solution
 2 {
 3 public:
 4     string convert(string s, int numRows)
 5     {//法一:找规律,计算数学表达式
 6     //参考:http://blog.csdn.net/linhuanmars/article/details/21145039
 7         if(s.size()==0 || numRows<=1 || s.size()<= numRows)//numRows=1是一种特殊情况,要单独考虑!!!
 8             return s;
 9         
10         string result;
11         int size = 2*numRows-2;//每个之字形是2*numRows-2个字符
12         //对每一行,先把往下的那列的字符加进去,然后将向上的字符加进去
13         for(int i=0; i<numRows; i++)//对于每一行
14         {
15             for(int j=i; j<s.size(); j+=size)
16             {
17                 result+=s[j];
18                 if(i!=0 && i!= numRows-1 && j+size-2*i < s.size())//注意表达式的计算!!!
19                     result += s[j+size-2*i];//对于非第一行和最后一行,加入向上的那个字符
20             }
21         }
22         return result;
23     }
24 };
25 int main()
26 {
27     Solution sol;
28     cout << sol.convert("PAYPALISHIRING",3)<<endl;//应输出:"PAHNAPLSIIGYIR"
29     cout << sol.convert("PAYPALISHIRING",4)<<endl;//应输出:"PINALSIGYAHRPI"
30     return 0;
31 }

 

法二:时间复杂度O(n),空间复杂度O(n)

     其实更容易想到

 1 class Solution
 2 {
 3 public:
 4     string convert(string s, int numRows)
 5     {//法二:用辅助空间,按照规则将其存在numRows个string中
 6     //参考:https://github.com/haoel/leetcode/blob/master/algorithms/zigZagConversion/zigZagConversion.cpp
 7         if(s.size()==0 || numRows<=1 || s.size()<= numRows)//numRows=1是一种特殊情况,要单独考虑!!!
 8             return s;
 9         vector<string> r(numRows);//!!!
10         int row = 0;//第几行
11         int step = 1;//标识向上还是向下
12         for(int i=0; i<s.size();i++)
13         {
14             if(row == numRows-1)//到达底部,反向
15                 step = -1;
16             if(row == 0)//到达顶部,反向
17                 step = 1;
18             r[row] += s[i];
19             row += step;
20         }
21         string result;
22         for(int i=0; i<numRows; i++)
23             result += r[i];
24         return result;
25     }
26 };

 

posted @ 2015-06-02 15:23  人生不酱油  阅读(143)  评论(0编辑  收藏  举报