leetcode-06-zigzag conversion-python

convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.

如图
将字符串以z型重新排列输出。OJ通过。

    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        a=['']*numRows
        if len(s)==1 or numRows==1:
            return s
        else:
            for i in range(1,len(s)+1):
                k=2*numRows-2
                m=i%k
                if 0<m<=numRows:
                    a[m-1]+=(s[i-1])
                if m>numRows and m <=k-1:
                    n=m-numRows
                    a[numRows-1-n]+=(s[i-1])
                if m==0:
                    a[1]+=(s[i-1])
        f=''.join(a)     
        return f

思路是找规律遍历字符串,按照索引值来计算在哪一行,对应那行的保存字符串,最后将所有行想加。
注意:

a=[1]*2
b=[[1]*2]
c=[[1]]*2
print(a,b,c)
print(len(a))
print(len(b))
[1, 1] [[1, 1]] [[1], [1]]
2
1
2
Press any key to continue . . .

如果想创建多维列表,用c的方式。
下面贴一个20ms过的cpp程序。

class Solution {
public:
    string convert(string s, int nRows) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function    
        if(nRows <= 1) return s;
        string ret;
        int zigsize = 2 * nRows - 2;
        for(int i = 0; i < nRows; ++i) {
            for(int base = i; ;base += zigsize) {
                if(base >= s.size())
                    break;
                ret.append(1,s[base]);
                if(i > 0 && i < nRows - 1) {
                    //middle need add ziggggging char
                    int ti = base + zigsize - 2 * i;
                    if(ti < s.size())
                        ret.append(1,s[ti]);
                }
            }
        }
        return ret;
    }
};

思路是一行行加s中特定元素。看起来两次循环。cpp就是比python快。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值