5 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 s, int numRows);
Example 1:

 Input: s = "PAYPALISHIRING", numRows = 3
 Output: "PAHNAPLSIIGYIR"

Example 2:

 Input: s = "PAYPALISHIRING", numRows = 4
 Output: "PINALSIGYAHRPI"

Explanation:

P I N
A L S I G
Y A H R
P I

如果不用二维数组按行打印输出的话,这道题目更考验数学的归纳总结能力,就是找规律:)我自己也找了一套规律写成了算法,运行速度还不错(84%),所以就贴在下面自己看看。

class Solution {
public:
    string convert(string s, int numRows) {
        
        string answer = "";
        
        int len = s.length();
        
        //check if the incoming string is null string
        if(len == 0) return answer;
        
        //if only one row, just return the original string
        
        if(numRows==1) return s;
        
        //else:
        vector<char> zig;
        
        int t = 2*(numRows-1);
        int col_count = 0;
        int int_count = 0;
        int idx = 0;
        
        while(col_count < numRows)
        {
            int add_num;
            
            if(int_count == 0) idx = col_count;
            else{
                
                if(col_count == 0 || col_count == (numRows-1))
                {
                    add_num = t;
                }
                else
                {
                    if(int_count%2 == 1) add_num = t - col_count*2;
                    else add_num = col_count*2;
                }
                
                idx += add_num;
                
            }
            
            
            if(idx < len)
            {
                zig.push_back(s[idx]);
                int_count++;
            }
            else{
                
                col_count+=1;
                int_count = 0;
                idx = 0;
            }
        }
        
        for(int i=0;i<zig.size();i++)
            answer += zig[i];
    
        
        return answer;
        
    }
};
posted @ 2019-07-10 05:48  孙小鸟  阅读(127)  评论(0编辑  收藏  举报