LeetCode6. Zigzag Conversion (Analog)

The main idea of ​​the title: draw the Z word continuously in the given string in the given number of lines, and then read the characters horizontally

Question analysis: This question only needs to simulate the process of drawing Z, and fill in the characters in the order of the columns.

I initialized the canvas with a two-dimensional matrix of numRows*len, initialized all grids to '\0', and then filled in characters by column.

There are two cases for the column: one is that each column has numRows characters, in this case, just fill in numRows characters in order;

Another case is that there is only one character in each column. In this case, it is necessary to calculate its row number and find that it is related to the modulus of the current column number and numRows.

row number = numRows - (column number %(numRows-1)) - 1 

In addition, if numRows=1 is handled separately, it can avoid the situation where the divisor is 0 later


Code display:

class Solution {
public:
    string convert(string s, int numRows) {
        int len = s.length();
        int numColms = 0;
        if(numRows!=1)
            numColms = only;
        else
            return s;
        char num[numRows][numColms];
        memset(num,'\0',sizeof(num));
        int k = 0;
        for(int i=0;i<numColms;i++){ //Analyze the i-th column
            int temp = i%(numRows-1);
            if(temp==0){ //Indicates that the column has more than one number
                for(int j=0;j<numRows;j++){
                    if(k>=len)   
                        break;
                    num[j][i] = s[k++];
                }
            }
            else{ //otherwise the column has only one number
                if(k>=len)   
                    break;
                num[numRows-temp-1][i] = s[k++];
            }
        }
        string str = "";
        for(int i=0;i<numRows;i++){
            for(int j=0;j<numColms;j++){
                 if(num[i][j]!='\0')
                    str += num[i][j];    
            }
        }
        return str;
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326038286&siteId=291194637