LeetCode | 6. ZigZag Conversion 循环技巧题
2018-01-30 16:50
85 查看
Thestring "PAYPALISHIRING" is written in a zigzag pattern on
a given number of rows likethis: (you may want to display this pattern in a fixed font for betterlegibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Writethe code that will take a string and make this conversion given a number ofrows:
string convert(string text, int nRows);
convert("PAYPALISHIRING",3) should return "PAHNAPLSIIGYIR".
字符串技巧题,只需要将给定的字符串按照列的方向输入string数组,然后按照行的方向输出string数组就能得到最终的结果class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s;
int index=0, c=0;
int n = s.size();
vector<string> theMark(numRows,"");
while (index < n)
{
while (c < numRows&&index < n)
{
theMark[c++].push_back(s[index++]);
}
c -= 2;
while (c >= 1&&index < n)
{
theMark[c--].push_back(s[index++]);
}
}
string result = "";
for (int i = 0; i < numRows; i++)
{
result.append(theMark[i]);
}
return result;
}
};
a given number of rows likethis: (you may want to display this pattern in a fixed font for betterlegibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Writethe code that will take a string and make this conversion given a number ofrows:
string convert(string text, int nRows);
convert("PAYPALISHIRING",3) should return "PAHNAPLSIIGYIR".
字符串技巧题,只需要将给定的字符串按照列的方向输入string数组,然后按照行的方向输出string数组就能得到最终的结果class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s;
int index=0, c=0;
int n = s.size();
vector<string> theMark(numRows,"");
while (index < n)
{
while (c < numRows&&index < n)
{
theMark[c++].push_back(s[index++]);
}
c -= 2;
while (c >= 1&&index < n)
{
theMark[c--].push_back(s[index++]);
}
}
string result = "";
for (int i = 0; i < numRows; i++)
{
result.append(theMark[i]);
}
return result;
}
};
相关文章推荐
- LeetCode | 121. Best Time to Buy and Sell Stock循环技巧题
- LeetCode | 27. Remove Element循环技巧题
- LeetCode | 1. Two Sum 简单循环技巧题
- LeetCode | 16. 3Sum Closest 循环技巧题
- LeetCode | 475. Heaters 循环技巧题
- LeetCode | 7. Reverse Integer 数字反向循环技巧题
- LeetCode | 219. Contains Duplicate II 循环技巧题高效率方法
- LeetCode | 55. Jump Game循环技巧题
- LeetCode | 27. Remove Element贪心算法循环技巧题
- 批处理技巧:循环固定目录的子目录,然后向每个子目录拷贝文件
- LeetCode | 693. Binary Number with Alternating Bits 二进制技巧题
- javascript中for/in循环及使用技巧
- leetcode 373. Find K Pairs with Smallest Sums 暴力循环求解
- R语言︱函数使用技巧(循环、if族/for、switch、repeat、ifelse、stopifnot)
- Javascript中快速退出多重循环的技巧
- dom元素循环绑定事件的技巧
- LeetCode 166 Fraction to Recurring Decimal (从分数到循环小数)(*)
- LeetCode刷题 | 726. Number of Atoms 难题 for循环处理题
- 传到freemarker页面一个List,本来要循环展示,但样式是五个一循环,处理技巧
- ecshop模板制作 中 foreach 循环次数的调用及使用技巧