Leetcode - ZigZag Conversion

Ji Kim·2020년 8월 24일
0

Algorithm

목록 보기
12/34

LeetCode : ZigZag Conversion

Description

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this

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:

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

// PINALSIGYAHRPI

Approach

First create a vector containing first numRows- amount of alphabets. And then accumulate the following alphabets for each index of the vector.

Solutions (C++)

Solution 1

class Solution {
public:
    string convert(string s, int numRows) {
        if (numRows == 1)
            return s;
        
        int length = s.length();
        int flag = 1; 
        int index = 0; 
        string answer = "";
        vector<string> array(numRows, "");

        for (int i = 0; i < length; i++)
        {
            array[index] += s[i];
            index += flag;

            if (!index || index == numRows - 1)
            {
                flag *= -1;
            }
        }

        for (int i = 0; i < array.size(); i++)
        {
            answer += array[i];
        }
        
        return answer;
    }
};

Result

Runtime: 28 ms
Memory Usage: 10.3 MB
Runtime Beats 66.84% of C++ Submission

Solution 2

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

Result

Runtime: 16 ms
Memory Usage: 8 MB
Runtime Beats 97.93% of C++ Submission

profile
if this then that

0개의 댓글