[LeetCode] ZigZag Conversion 解题报告
来源:互联网 发布:fpga用什么软件 编辑:程序博客网 时间:2024/06/06 01:22
—— write for my baby, mua
[题目]
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"
.[中文翻译]
字符串"PAYPALISHIRING"
写成给定行数的ZigZag模式如下:(为了更好的可读性,你可能需要以固定字体显示这个模式)
P A H NA P L S I I GY I R然后将该模式按行读:
"PAHNAPLSIIGYIR"
给定字符串和行数,编写代码完成这个转换:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)
返回 "PAHNAPLSIIGYIR"
。[解题思路]
zigZag模式,即将原来的字符串,按下图方式依次排列。
图1. ZigZag模式
O(M+N) M=len(text), N=nRows
如果nRows<=1,则直接返回text
否则,创建N个字符串,分别表示ZigZag模式的N行。遍历text的字符,将字符循环往复地插入N个字符串中,可以用一个指针(整数)表示当前字符要插入第几个字符串。
最后,将N个字符串连接,返回结果。
[C++代码]
class Solution {public:string convert(string s, int numRows) {if (numRows <= 1)return s;string* line = new string[numRows];int index = 0, dircetion = 1, lineIndex = 0;while (index < s.size()) {if (lineIndex < 0) {lineIndex = 1;dircetion = -dircetion;}else if (lineIndex >= numRows) {lineIndex = numRows - 2;dircetion = -dircetion;}line[lineIndex] = line[lineIndex] + s.at(index);index++;lineIndex += dircetion;}string res = "";for (int i = 0; i < numRows; i++)res = res + line[i];return res;}};
0 0
- 【LeetCode】ZigZag Conversion 解题报告
- LeetCode ZigZag Conversion 解题报告
- LeetCode解题报告--ZigZag Conversion
- [LeetCode] ZigZag Conversion 解题报告
- [LeetCode] ZigZag Conversion 解题报告
- Leetcode ZigZag Conversion解题报告
- [leetcode] 6. ZigZag Conversion 解题报告
- LeetCode 6. ZigZag Conversion 解题报告
- [Leetcode] 6. ZigZag Conversion 解题报告
- leetcode解题报告6. ZigZag Conversion
- [LeetCode 解题报告]006.ZigZag Conversion
- 【LeetCode】6.ZigZag Conversion(Medium)解题报告
- LeetCode(6) ZigZag Conversion解题报告
- ZigZag Conversion解题报告
- LeetCodeProblem6 ZigZag Conversion解题报告
- LeetCode解题报告 6. ZigZag Conversion[easy]
- 【Leetcode】6.ZigZag Conversion 解题
- [Leetcode]解题文档-ZigZag Conversion
- 有功功率、无功功率、视在功率、之间的联系
- hdu 1556 Color the ball
- 欢迎使用CSDN-markdown编辑器
- 基于地图的短信追踪小练习(2)百度地图定位到自己的位置
- 目录
- [LeetCode] ZigZag Conversion 解题报告
- Android报错:JNI相关“ Error: NDK integration is deprecated in the current plugin.”
- getaddrinfo()函数详解
- MQ实现两个应用系统之间的通信----理论知识(一)
- IT学习网站总结
- Maven常用命令 - 构建反应堆中指定模块
- 软件打包工具NSIS安装程序制作系统
- 使用V3.5打包服务器打包IOS报错
- 宿主机无法访问虚拟机 hadoop centos6