zoukankan      html  css  js  c++  java
  • 6. ZigZag Conversion

    题目:

    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 text, int nRows);

    convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

    代码:

    看了半天,都没怎看懂题目。查了一下,原来:

    Zigzag:即循环对角线结构(

    0       8       16      
    1     7 9     15 17      
    2   6   10   14   18      
    3 5     11 13     19      
    4       12       20      

    这样子的话,就不算麻烦了,只要正确的字符串操作,把每个元素加在正确的位置就好。

    于是,共有numRows行,所以定义一个保护numRows元素的数组,用来保存每一行的字符串。

    观察规律,第一列从0写到numRows-1,之后从后往前,及numRows-2到0开始逐渐添加。输出并不需要考虑宽度,所以对字符串来说,之后往后加就好

    //凑了半天,总算凑出来了

    def convert(self, s, numRows):
            """
            :type s: str
            :type numRows: int
            :rtype: str
            """
            i = 0
            j = 0
            gap = numRows-2
            temp= ['' for x in range(numRows)]
            while i<len(s):
                while(j<numRows):
                    if(i>=len(s)):break
                    temp[j] += str(s[i])
                    j += 1
                    i += 1
                j=gap
                while(j>0):
                    if(i>=len(s)):break
                    temp[j] += str(s[i])
                    j -= 1
                    i += 1
            result = ''
            for y in temp:result += y

            return result    

    //网上查的,好像更直观   
        def convert2(self, s, nRows):
            if nRows==1: return s
            tmp=['' for i in range(nRows)]
            index=-1; step=1
            for i in range(len(s)):
                index+=step
                if index==nRows:
                    index-=2; step=-1
                elif index==-1:
                    index=1; step=1
                tmp[index]+=str(s[i])
            return ''.join(tmp)

    测试了多次,两个速度差不多,必定时间复杂度和空间复杂度都一样:

  • 相关阅读:
    Linux CentOS7.0 (04)systemctl vs chkconfig、service
    SpringCloud是否值得引入?
    SpringCloud的Hystrix(二) 某消费者应用(如:ui、网关)访问的多个微服务的断路监控
    SpringCloud的Hystrix(一) 一个消费者内的两个服务监控
    SpringCloud的Bus(一)消息中间件的概念和用途
    api-gateway实践(13)新服务网关
    SpringCloud应用入库后乱码问题
    SpringCloud的应用发布(四)vmvare+linux,网关代理
    SpringCloud的DataRest(四)restful特性展示
    win10 如何让其他机器访问自己机器上的mysql
  • 原文地址:https://www.cnblogs.com/yuanzhaoyi/p/5952517.html
Copyright © 2011-2022 走看看