Accepted Swift solution. Not as fast as fastest, but clear and commented


  • 0
    F

    This code runs in about 50 ms. It uses multiple extensions to make the intended function clear to read, and is simple & direct.

    extension Array {
        mutating func popfirst() -> Element? {
            guard !self.isEmpty else {return nil}
            let v = self.first!
            self.remove(at: 0)
            return v
        }
    }
    
    // ["12345", "abcdef"].length = 5 + 6 =11
    extension Sequence where Iterator.Element == String {
        var length: Int {
            return self.reduce(0) {$0 + $1.count}
        }
    }
    
    // "abcdef".count = 6. Underlying code operates on utf16 code points
    extension String {
        var count: Int { return distance(from: startIndex, to: endIndex) }
    
    }
    
    class Solution {
        func fullJustify(_ words: [String], _ maxWidth: Int) -> [String] {
            var words = words
            var result = [String]()
    
            /*
             * loop while there are words left to insert into lines.
             * words: array of word strings
             * result: array of line strings as output
             */
            while !words.isEmpty {
                var line = [words.popfirst()!]
    
                /*
                 * loop to determine the additional words that will go on the current line,
                   before adjusting for inter-word spaces exceeding the first.
                 * line: array or word strings that will go on the current line
                 */
                while let w = words.first, w.count + line.length + line.count <= maxWidth {
                    line.append(words.popfirst()!)
                }
    
                /*
                 * insert first word into line
                 */
                var linestring = line.popfirst()!
    
                /*
                 * loop to insert words from line array into linestring
                 */
                while !line.isEmpty {
    
                    /*
                     * actualspacer: number of spaces that will precede the next word being added, rounding up
                     */
                    let spacer = words.isEmpty ? 1 : (maxWidth - linestring.count - line.length + line.count - 1) / line.count
                   linestring += String(repeating: " ", count: spacer) + line.popfirst()!
                }
    
                /*
                 * Append trailing blanks on last line
                 */
                linestring += String(repeating: " ", count: max(0, maxWidth - linestring.count))
                result.append(linestring)
            }
            return result
        }
    }
    

Log in to reply
 

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