LeetCode算法题——ZigZag Conversion
2017-03-09 21:46
232 查看
Description:
The string
like this: (you may want to display this pattern in a fixed font for better legibility)
And then read line by line:
Write the code that will take a string and make this conversion given a number of rows:
return
Zigzag:即循环对角线结构(
)
算法思想:
向下循环
斜对角循环:gap=nRows-2(去除端点)
C++ Implements:
string convert(string s, int numRows) {
if(numRows==1) return s;
string str[numRows];
int i=0,gap=numRows-2;
while(i<s.size()){
for(int j=0;j<numRows&&i<s.size();j++){
str[j]+=s[i++];
}
for(int j=gap;j>0&&i<s.size();j--){
str[j]+=s[i++];
}
}
string res="";
for(int j=0;j<numRows;j++){
res+=str[j];
}
return res;
}
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 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"
Zigzag:即循环对角线结构(
0 | 8 | 16 | |||||||||
1 | 7 | 9 | 15 | 17 | |||||||
2 | 6 | 10 | 14 | 18 | |||||||
3 | 5 | 11 | 13 | 19 | |||||||
4 | 12 | 20 |
算法思想:
向下循环
斜对角循环:gap=nRows-2(去除端点)
C++ Implements:
string convert(string s, int numRows) {
if(numRows==1) return s;
string str[numRows];
int i=0,gap=numRows-2;
while(i<s.size()){
for(int j=0;j<numRows&&i<s.size();j++){
str[j]+=s[i++];
}
for(int j=gap;j>0&&i<s.size();j--){
str[j]+=s[i++];
}
}
string res="";
for(int j=0;j<numRows;j++){
res+=str[j];
}
return res;
}
相关文章推荐
- [leetcode.com]算法题目 - Remove Duplicates from Sorted List
- leetcode -- 一个算法面试题相关的网站
- leetcode:Longest Substring Without Repeating Characters (双指针扫描) 【面试算法题】
- leetcode:Merge Intervals(合并相交集合) 【面试算法题】
- [leetcode.com]算法题目 - Length of Last Word
- 算法。递归。之一: combination sum, leetcode
- Longest Valid Parentheses(最长的括号匹配)【面试算法leetcode】
- [leetcode.com]算法题目 - Restore IP Addresses
- leetcode:Median of Two Sorted Arrays (找两个序列的中位数,O(log (m+n))限制) 【面试算法】
- [leetcode.com]算法题目 - Triangle
- [leetcode.com]算法题目 - Pascal's Triangle
- leetcode:Distinct Subsequences (不同的子序列)【面试算法题】
- Longest Palindromic Substring (最长回文串)【面试算法leetcode】
- [leetcode.com]算法题目 - Jump Game
- [leetcode.com]算法题目 - Same Tree
- [leetcode.com]算法题目 - Decode Ways
- [leetcode.com]算法题目 - Maximum Subarray
- Maximal Rectangle (求矩阵的最大的子矩阵) 【面试算法leetcode】
- [leetcode.com]算法题目 - Sqrt(x)
- leetcode:Merge k Sorted Lists(按大小顺序连接k个链表)【面试算法题】