6. ZigZag Conversion

本文介绍了一种将字符串以Zigzag形式排列并按行读取的算法实现。通过两个不同方法展示如何将输入字符串PAYPALISHIRING转换为PAHNAPLSIIGYIR。详细解释了代码逻辑,并附带了实际测试结果。

题目:

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  79  1517   
2 6 10 14 18   
35  1113  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)

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

转载于:https://www.cnblogs.com/yuanzhaoyi/p/5952517.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值