leetcode系列(25)ZigZag Conversion 锯形转化
来源:互联网 发布:淘宝学习网站 编辑:程序博客网 时间:2024/04/28 06:06
ZigZag Conversion
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 NA P L S I I GY I RAnd 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"
.构造一个二维字符数组(vector<string>),按照zigzag的方式填充,就是拼接数组的每行字符串,输出就是了。填充过程中,
按列填充,第一列从第一行填充到最后一行,第二列则从最后一行填充到第一行,如此反复,直至填充完毕。
C++代码
class Solution {public: string convert(string s, int numRows) { vector<string> ret(numRows, string("")); int cur_row = 0; int step = 1; if (numRows <= 1 || numRows >= s.size()) { return s; } for (int i = 0; i < s.size(); ++i) { ret[cur_row].push_back(s[i]); if (cur_row == 0) { step = 1; } if (cur_row == (numRows - 1)) { step = -1; } cur_row += step; } string zig_string(""); for (auto item = ret.begin(); item != ret.end(); ++item) { zig_string += (*item); } return zig_string; }};
Python代码
class Solution: # @param {string} s # @param {integer} numRows # @return {string} def convert(self, s, numRows): if numRows <= 1 or numRows >= len(s): return s ret = [""] * numRows cur_row = 0 step = 1 for i in range(0, len(s)): ret[cur_row] += s[i] if cur_row == 0: step = 1 if cur_row == (numRows - 1): step = -1 cur_row += step zig_string = "" for item in ret: zig_string += item return zig_string
0 0
- leetcode系列(25)ZigZag Conversion 锯形转化
- leetcode:ZigZag Conversion锯行转换
- LeetCode(6) ZigZag Conversion
- LeetCode (6)ZigZag Conversion
- [leetcode刷题系列]ZigZag Conversion
- LeetCode | ZigZag Conversion(锯齿形转换)
- LeetCode 题解(68): ZigZag Conversion
- leetcode第六题 ZigZag Conversion (java)
- Leetcode日记(6)---ZigZag Conversion
- LeetCode 6. ZigZag Conversion(之字形)
- Leetcode题解(Python): 6. ZigZag Conversion
- LeetCode进阶之路(ZigZag Conversion)
- 【LeetCode算法练习(C++)】 ZigZag Conversion
- LeetCode: ZigZag Conversion
- LeetCode : ZigZag Conversion
- leetcode 13:zigzag conversion
- [LeetCode] Zigzag Conversion
- LeetCode 6 - ZigZag Conversion
- 14个Xcode中常用的快捷键操作
- 自动化测试 之亡羊补牢编
- 欢迎使用CSDN-markdown编辑器
- 通过JDBC操作数据库的标准示例
- Web安全之文件操作
- leetcode系列(25)ZigZag Conversion 锯形转化
- android数据库——GreenDao
- Developer--AsyncTask
- Mac maven 的安装
- ibooking项目设计介绍(一个基于SSH的外卖点餐系统)
- 【哥德巴赫猜想】POJ Goldbach's Conjecture 2262
- 二叉树的前、中、后遍历递归和非递归java实现
- Linux中Cron任务间隔执行:每隔几分钟/几小时/几天
- hpp 和 h 区别