【leetcode】ZigZag Conversion
来源:互联网 发布:0verture for mac 编辑:程序博客网 时间:2024/06/05 21:50
"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"
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
以上是题目。
先来说说思路,可能有些同学不知道什么是zigzag.我举个栗子:
1 7 13
2 6 8 12
3 5 9 11
4 10
就是如上这些形式啦。
那么我们可以很显然的得出规律,不看斜的,每行数字之间的间隔是 n*2 - 2;n是行数。除了第一行和最后一行以外,其余各行中间会插一个数,然而这个数也是有规律的,这个数是j+n*2 -2 -2*I;j指的是插入这个数之前那个数,i表示目前在第i行,于是很容易得到以下代码。
class Solution {
public:
string convert(string s, int numRows) {
int len = s.length();
if(len<2 || numRows == 1)return s;
string arry;
int t = 2*numRows-2;
for(int i = 0;i<numRows;i++){
for(int j = i;j<len;j+=t){
arry.push_back(s[j]);
if(i>0 && i<numRows-1 && j+t-2*i < len){
arry.push_back(s[j+t-2*i]);
}
}
}return arry;
}
};
- LeetCode: ZigZag Conversion
- LeetCode : ZigZag Conversion
- leetcode 13:zigzag conversion
- [LeetCode] Zigzag Conversion
- LeetCode 6 - ZigZag Conversion
- Leetcode : ZigZag Conversion
- 【leetcode】Zigzag Conversion
- [LeetCode]ZigZag Conversion
- leetcode ZigZag Conversion
- LeetCode-ZigZag Conversion
- LeetCode ZigZag Conversion
- LeetCode 6: ZigZag Conversion
- leetcode-006:ZigZag Conversion
- Leetcode: ZigZag Conversion
- [LeetCode]ZigZag Conversion
- [LeetCode] ZigZag Conversion
- [LeetCode]ZigZag Conversion
- leetcode: ZigZag Conversion
- 我的感想十五
- spring配置文件
- GlobalFreePtr()/GlobalAllocPtr()
- android知乎小圆圈刷新效果
- IntelliJ IDEA 添加对 Extjs6 支持
- 【leetcode】ZigZag Conversion
- 极路由安装ShadowsShcks插件
- Splay Tree(伸展树)
- 使用 Node 创建 RESTful 应用
- CDH5.3.x安装准备工作以及遇到的一些问题
- 性能调优工具TraceView
- Python正则表达式的七个使用范例
- “IE11主页设置已损坏,Internet Explorer重置了你的主页”详细解决办法
- inline修饰函数