Python with explanation


  • 6

    Given [‘AB’, ‘CDE’, ‘F’, …, ‘YZ’]
    Width: w

    1. join the words with empty space
    2. get the index of the end of a screen line w - 1

    there are 3 cases:

    Case 1:
    “AB-CDE-F-….-YZ” (‘-’ denotes a space)
    reach to the space before F

    Case 2:
    “AB-CDE-F-…._YZ” (‘-’ denotes a space)
    reach to exactly E

    Case 3:
    “AB-CDE-F-….-YZ” (‘-’ denotes a space)
    reach to D

    case 1, I can count one more bit and go to next line
    case 2, I can count two more bits and go to next line
    case 3, I have to move the cursor back until it reach to some space, and go to next line

    When I go through all the rows, how many bits did I counted? Let’s say L, then the answer should be L / length of the string

    class Solution(object):
        def wordsTyping(self, sentence, rows, cols):
            s = ' '.join(sentence) + ' '
            start = 0
            for i in xrange(rows):
                start += cols - 1
                if s[start % len(s)] == ' ':
                    start += 1
                elif s[(start + 1) % len(s)] == ' ':
                    start += 2
                else:
                    while start > 0 and s[ (start - 1) % len(s) ] != ' ':
                        start -= 1
            return start/ len(s)
    

Log in to reply
 

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