LeetCode 6 - ZigZag Conversion
来源:互联网 发布:乐视电视mac地址 编辑:程序博客网 时间:2024/04/29 20:07
一、问题描述
Description: 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 R
And 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"
.
根据给出的行数,按 “之” 字形排列源字符串,然后一行一行地输出字符串。
二、解题报告
本题主要是理解题意,输入一个字符串和一个行数,按“之”字形排列该字符串的字符,如下图:
这是 3 行的之字形,如果是 4 行的话:
以此类推。
思路:根据上面分析的规律,我们只需定义一个字符串数组,大小为行数(即每一行对应一个字符串)。然后遍历输入字符串,将每个字符插入对应行的字符串即可。
class Solution {public: string convert(string s, int numRows) { if(numRows == 1) return s; vector<string> v(numRows,""); // 创建numRows个字符串 int idx = 0; bool flag = true; for(int i=0; i<s.size(); ++i) { v[idx] += s[i]; if(flag) ++idx; else --idx; if(idx == numRows-1) flag = false; if(idx == 0) flag = true; } // 输出 string output = ""; for(int i=0; i<numRows; ++i) output += v[i]; return output; }};
LeetCode答案源代码:https://github.com/SongLee24/LeetCode
0 0
- LeetCode 6 - ZigZag Conversion
- LeetCode 6: ZigZag Conversion
- LeetCode(6)ZigZag Conversion
- Leetcode【6】:ZigZag Conversion
- [leetcode 6] ZigZag Conversion
- LeetCode 6 ZigZag Conversion
- LeetCode(6) ZigZag Conversion
- [Leetcode] 6 - ZigZag Conversion
- LeetCode 6:《ZigZag Conversion》
- [leetcode 6] ZigZag Conversion
- LeetCode | #6 ZigZag Conversion
- [leetcode] 6 ZigZag Conversion
- leetCode #6 ZigZag Conversion
- leetcode 6 ZigZag Conversion
- leetcode-6 ZigZag Conversion
- leetcode 6 ZigZag Conversion
- LeetCode 6 - ZigZag Conversion
- leetcode 6ZigZag Conversion
- 原局凶存,大运流年体现,早亡命例。
- WebRTC的问题
- hdu3047 Zjnu Stadium
- Python进阶(二)——Python对象类型
- myBatis学习笔记(5)——一对多关联表查询
- LeetCode 6 - ZigZag Conversion
- MSRCR(Multi-Scale Retinex with Color Restore)
- vm10.0.3安装Ghost win8
- Intl Extension missing on Xampp
- webview与js交互
- 欢迎使用CSDN-markdown编辑器
- 一起talk Vim吧(第十四回:Vim插件之配置文件)
- linux应用开发-I/O2
- html中的应用小技巧