美文网首页
006-zigzag conversation

006-zigzag conversation

作者: 英武 | 来源:发表于2019-04-10 11:31 被阅读0次

zigzag conversation

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);

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

设置一个字符串数组,然后其实就是设置边界条件,然后根据所处的位置决定向前还是向后。

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows == 1 or numRows >= len(s):
            return s

        L = [''] * numRows
        index, step = 0, 1

        for x in s:
            L[index] += x
            if index == 0:
                step = 1
            elif index == numRows -1:
                step = -1
            index += step

        return ''.join(L)

相关文章

  • 006-zigzag conversation

    zigzag conversation The string "PAYPALISHIRING" is writte...

  • KEY TO FURTHER PRACTICE IN LISTE

    UNIT 1 SHORT CONVERSATION: BABDD LONG CONVERSATION: DBCD ...

  • [笔记·英语口语]|b站·跟外教Ronnie学英语口语日常·第二

    Conversation Skills How to avoid a conversation? 1.Don't ...

  • Conversation

    I love sport So .Justin What do you do in your free time?...

  • conversation

    像是过去,现在与未来以奇异的方法组合起来 你看到分解场景中的想法聚合在一起 也可以选择让感觉流失 也可以选择把它归...

  • Conversation

    在看完这个演讲之后有种恍然大悟的感觉,演讲者是以做主持人的经验告诉我们如何成为一个更好的交谈者,将这样的方式带入到...

  • Conversation

    好久没有联系的老师今天突然又联系了。他是大学时的听力老师。突然聊到他女儿快要高考,时间过得可真快。当初还在校园时他...

  • conversation

    妹纸微信分享给我一首好听的歌,安静低回的旋律仿佛在轻轻述说一个故事,那种淡淡的情,浅浅的爱,就像初夏的一场雨,或是...

  • 托福听力1

    Tpo1-Conversation1 Listen to part of a conversation betwe...

  • 情绪管理

    在KELVIN课堂《Crucial Conversation》测试上获得Conversation Master的做...

网友评论

      本文标题:006-zigzag conversation

      本文链接:https://www.haomeiwen.com/subject/fpcniqtx.html