leetcode-06-zigzag conversion-python

来源:互联网 发布:mac 10.11.6 双系统 编辑:程序博客网 时间:2024/06/01 09:59

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]*2b=[[1]*2]c=[[1]]*2print(a,b,c)print(len(a))print(len(b))
[1, 1] [[1, 1]] [[1], [1]]212Press 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快。

0 0