Solution for ZigZag(Swift)


  • 0
    N

    At first glance,the problem is a math problem,something like dividing all characters of a string into n arrays which corresponding to numRows. It's better to put character arrays into a array for it easier to get a character array using the index.

    The major steps have already taken shape.
    1.Create a array of string to save character in n rows. array[0] saves character in row 0, array[1] saves character in row 1, and so on.
    2.Append the character of index x into the right string in array.
    3.Join all strings together and return it.

    STEP 1:

    var stringArray = Array(repeating: "", count: numRows)
    

    STEP 2:

    In this step, a character in which row in the main problem. That's take a look at a zigzag pattern again:

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

    1.This can be divided to several loops, First P to the Second P is the first loop, sceond A to S is the second loop, and so on. Every zigzag pattern fits the rule.

    The number of loop characters is n + (n - 2) = 2*(n-1), when n = 1, the count is 0, so we should handle this situation before the first step.

    if numRows <= 1{
       return s
    }
    

    2.Then, in every loop, how to get the right row number? When character is in the vertical line, the row number is increasing from 0, otherwise, the number is decreasing from n. So we know a character in which row in this way.

    1. append current character to the right string.
    for (index, theChar) in s.enumerated(){
                //1
                var loopLength = 2*(numRows-1)
                let remainder = index % loopLength
                var arrayIndex = -1
                //2
                if (remainder < numRows){
                    arrayIndex = remainder
                }else{
                    arrayIndex = loopLength - remainder 
                }
                //3
                var theString = stringArray[arrayIndex]
                theString.append(theChar)
                stringArray[arrayIndex] = theString
            }
    

    STEP 3:

    var result = ""
            for str in stringArray{
                result += str
            }
    return result 
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.