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
- leetcode-06-zigzag conversion-python
- [Leetcode] ZigZag Conversion @Python
- 【Leetcode】【python】ZigZag Conversion
- LeetCode 06 ZigZag Conversion
- Leetcode 06 ZigZag Conversion
- 【LeetCode with Python】 ZigZag Conversion
- 6. ZigZag Conversion Leetcode Python
- 【LeetCode with Python】 ZigZag Conversion
- [Leetcode]6. ZigZag Conversion @python
- [leetcode: Python]6. ZigZag Conversion
- Leetcode题解(Python): 6. ZigZag Conversion
- LeetCode 6. ZigZag Conversion(Python)兼翻译
- LeetCode: ZigZag Conversion
- LeetCode : ZigZag Conversion
- leetcode 13:zigzag conversion
- [LeetCode] Zigzag Conversion
- LeetCode 6 - ZigZag Conversion
- Leetcode : ZigZag Conversion
- C语言运算符优先级记忆
- sql server 数据库目录名无效解决办法
- Android 属性动画(Property Animation) 完全解析【附源码】
- 异步访问----Android AsyncTask 源码解析
- ACE开发学习总结
- leetcode-06-zigzag conversion-python
- 码流 / 码率 / 比特率 / 帧速率 / 分辨率 / 高清
- caffe-stn移植到高版本的方法
- cocos2dx 防御式编程模式
- 安装系统经验总结
- 汇编笔记整理
- 如何实现viewpager自动轮播
- 服务器安装字体库解决出现xx问题
- 关于shared_ptr