Skip to content

Commit

Permalink
added 9. ZigZag Conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
pezy committed Jan 22, 2015
1 parent 38ceafa commit 0f4a413
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
10 changes: 10 additions & 0 deletions 99. ZigZag Conversion/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
说实话,不太喜欢这种题。觉得娱乐性远大于对知识点考查。

况且解析字符串也百无聊奈。

这道题为了效率,肯定希望在一次迭代中完成对字符串的分组。而经过简单的分析,可以发现迭代的索引与分组的索引有非常规律的对应关系。

- 对(nRows-1)取余,可以区分行数。
- 对(nRows-1)做除,可以区分当前是上升还是下降(偶数上升,奇数下降)。

主要策略就是这样了。代码总共五行,一看果然是 Easy 档次。
10 changes: 10 additions & 0 deletions 99. ZigZag Conversion/TEST.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#define CATCH_CONFIG_MAIN
#include "../Catch/single_include/catch.hpp"
#include "solution.h"

TEST_CASE("ZigZag Conversion", "[convert]")
{
Solution s;
REQUIRE( s.convert("PAYPALISHIRING", 3) == "PAHNAPLSIIGYIR" );
REQUIRE( s.convert("ABCDE", 4) == "ABCED" );
}
18 changes: 18 additions & 0 deletions 99. ZigZag Conversion/solution.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#include <string>
using std::string;
#include <vector>
#include <numeric>


class Solution {
public:
string convert(string s, int nRows) {
if (s.empty() || nRows < 2) return s;
std::vector<string> ret(nRows);
for (size_t i=0; i<s.size(); ++i) {
int m = i % (nRows-1), n = i / (nRows-1);
(n & 0x1 ? ret[nRows-m-1] : ret[m]) += s[i];
}
return std::accumulate(ret.cbegin(), ret.cend(), string());
}
};

0 comments on commit 0f4a413

Please sign in to comment.