forked from pezy/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
说实话,不太喜欢这种题。觉得娱乐性远大于对知识点考查。 | ||
|
||
况且解析字符串也百无聊奈。 | ||
|
||
这道题为了效率,肯定希望在一次迭代中完成对字符串的分组。而经过简单的分析,可以发现迭代的索引与分组的索引有非常规律的对应关系。 | ||
|
||
- 对(nRows-1)取余,可以区分行数。 | ||
- 对(nRows-1)做除,可以区分当前是上升还是下降(偶数上升,奇数下降)。 | ||
|
||
主要策略就是这样了。代码总共五行,一看果然是 Easy 档次。 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" ); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | ||
} | ||
}; |