Leetcode Zigzag Conversion problem solution in C

In the Leetcode Zigzag Conversion problem solution in C programming 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);

Leetcode Zigzag Conversion problem solution in C programming

#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

char * convert(char * s, int numRows){
    //return the original string if there's only one row
    if (numRows == 1) {
        return s;
    }
    
    char *ans = (char*)malloc(sizeof(char) * (strlen(s) + 1));
    memset(ans, 0, sizeof(char) * (strlen(s) + 1));
    
    char zigzag_arr[numRows][1001];
    memset(zigzag_arr, 0, sizeof(char) * numRows * 1001);
    
    int row_idx = 0, col_idx[numRows];    //store the indices of the columns in "col_idx" array
    memset(col_idx, 0, sizeof(int) * numRows);  //set all elements in col_idx[] to 0
    bool down = true;
    
    for (int i = 0; i < strlen(s); i++) {
        //increase col_idx[row_idx] after adding a char to the end of zigzag_arr[row_idx]
        zigzag_arr[row_idx][col_idx[row_idx]++] = s[i];
        
        //change row_idx direction when meet the edges
        if (row_idx == (numRows-1)) {
            down = false;
        } else if (row_idx == 0) {
            down = true;
        }
        
        //increase or decrease row_idx according to current direction
        if (down == true) {
            row_idx++;
        } else {
            row_idx--;
        }
    }
    
    //concatenate the strings to ans
    for (int i = 0; i < numRows; i++) {
        strncat(ans, zigzag_arr[i], sizeof(char) * strlen(zigzag_arr[i]));
    }
    
    return ans;
}

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *