LeetCode题解 week14
来源:互联网 发布:网络搞笑日语中文谐音 编辑:程序博客网 时间:2024/06/15 04:54
6.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 N
A P L S I I G
Y 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”.
所谓的zigzag pattern型就是指,我们以倒N型的顺序来读数。
三行的情况:
四行的情况:
我们输入的text是以这种模式来排布的,之后我们需要将其以横向的、从左到右的、我们习惯的阅读方式来从新排布,将其输出。
一种解题思路就是,我们使用数个字符串(设为row[n]),存下每一行的字符,最后将每行的字符串叠连起来,就是我们想要的结果。以一次下、一次上为一个单元(一共2*nRows-2个字符),这样我们就能算出每个输入的text中的每个字符分别对应某个单元的第几个字符,也就可以计算得到改字符的行数。也就是说,我们能够计算出text[i],text的第i个字符是属于第几行的,之后将其添加到row中。这样,我们只需要走一次text,就能够得到每行依此有哪些字符,之后将其首尾相连,得到的就是输出了。
参考代码如下:
class Solution {public: string convert(string s, int numRows) { int len = s.length(); if(len <= 1 || numRows == 1) return s; string temp[numRows]; for(int i = 0; i < numRows; i++) temp[i] = ""; for(int i = 0; i < len; i++) { int index = i % (2*numRows-2); if(index >= numRows) index = 2 * numRows - 2 - index; temp[index] += s[i]; } string result = ""; for(int i = 0; i < numRows; i++) result += temp[i]; return result; }};
- LeetCode题解 week14
- leetcode week14
- Leetcode Week14
- week14-leetcode #121-BestTimetoBuyandSellStock
- LeetCode Week14: Longest Valid Parentheses
- LeetCode#648 Replace Words (week14)
- LeetCode#554 Brick Wall (week14)
- LeetCode#494 Target Sum (week14)
- Leetcode: 216. Combination Sum III(Week14, Medium)
- 算法设计Week14 LeetCode Algorithms Problem #91 Decode Ways
- Leetcode 416 Partition Equal Subset Sum (算法分析week14)
- [LeetCode-Algorithms-75] "Sort Colors" (2017.12.7-WEEK14)
- [LeetCode-Algorithms-537] "Complex Number Multiplication" (2017.12.7-WEEK14)
- Leetcode 646. Maximum Length of Pair Chain(算法分析week14)
- leetcode题解
- leetcode题解
- LeetCode 题解
- leetCode题解
- 【区间dp】HDU6212 Zuma 经典题
- AutoCAD .Net 程序的初始化和退出函数
- JavaScript的instanceof运算符
- git底层原理以及丢失文件找回和坑爹案例
- CSS媒体查询和flex实现自适应多栏布局
- LeetCode题解 week14
- 排序算法比较
- C/C++ --数组和指针的关系
- Recyclerview自定义点击事件(以及Fresco中SimpleDraweeView的使用)
- JDK和JRE的区别
- 阿里云连接jupyter notebook的步骤
- Ubuntu 16.04安装搜狗输入法
- C语言实验——数日子
- python入门(一)