zigzag

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)

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"

方法1:遍历每次首行和最后一行改变方向(所为方向就是行++和行--)

class Solution {
public:
    string convert(string s, int numRows) {
        
        if (1 >= numRows) {
            return s;
        }        
        
        int length = s.length();
        int curRow = 0;
        int direct = 1;
        
        string out[numRows];
        
        for(int i = 0; i < length; i++) {   
            out[curRow] += s[i];
            
            if(0 == curRow) {
                direct = 1;
            }
            
            if(numRows - 1 == curRow ) {
                direct = -1;
            }
            curRow += direct;
        }
    
        string result = "";  
        for(int i = 0; i < numRows; i++){  
            result += out[i];  
        }  
        return result; 
    }
};

方法2:分组,每组行数*2-2个,首行和末行各一,其余各行各2,秩序计算一下通用公式即可;

class Solution {
public:
    string convert(string s, int numRows) {
        
        if (1 >= numRows) {
            return s;
        }        
        string out = "";
        
        int length = s.length();
        int temp = 2 * numRows -2;
       
        for(int i = 0; i < numRows; i++) {   
            int curTemp = 0;
            while(curTemp * temp + i < length) {
                out += s[curTemp * temp + i];
                if(0!=i && numRows-1!=i && (curTemp+1)*temp-i

你可能感兴趣的:(zigzag)