leetcode zigzag conversion

https://leetcode.com/problems/zigzag-conversion/


思路1

其实这里只需要找出一般公式就行,没什么技巧。当i是1到n-2行时,第i行第一个在斜线上的元素在s中的index是 2 numRows - 2, 所以与第i行第一个元素 i (以及后面增加2 numRows - 2后的j),相差 2 numRows - 2 - 2 i个元素。


my code:

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if len(s) == 1 or numRows == 1:
            return s
        res = []
        for i in xrange(numRows):
            j = i
            while j < len(s):
                res.append(s[j])
                if i >0 and i < numRows - 1:
                    tmp = j + 2*numRows -  2 - 2*i
                    if tmp < len(s):
                        res.append(s[tmp])
                j += 2*numRows - 2

        return "".join(res)

思路2

http://www.cnblogs.com/zuoyuan/p/3777745.html


其中index是tmp中哪一行的index,这个index的变化是0,1,2,..., nRow - 1, nRow(这个值已经是在斜线上的元素) ->转换成nRow - 2, nRow - 3, ..., 2, 1, 0, -1->转化成1,2,...

这里step就是1和-1,用来调整index的运动方向的

class Solution:
    # @return a string
    def convert(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]+=s[i]
        return ''.join(tmp)

思路3

直接把zigzag放到2Dmatrix里面,然后输出就行了。


http://yucoding.blogspot.hk/2013/02/leetcode-question-125-zigzag-conversion.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值