From 32d4d04204f1f7492e702b9f754bc69e2ab9bb5a Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Tue, 1 Mar 2022 23:35:17 +0800 Subject: [PATCH] add: 220301-CN [cpp] --- cpp/2203/220301-CN.cpp | 68 +++++++++++++++++++++++++++++++++++++++++ cpp/2203/CMakeLists.txt | 6 ++++ cpp/CMakeLists.txt | 5 +-- 3 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 cpp/2203/220301-CN.cpp create mode 100644 cpp/2203/CMakeLists.txt diff --git a/cpp/2203/220301-CN.cpp b/cpp/2203/220301-CN.cpp new file mode 100644 index 0000000..84f68c9 --- /dev/null +++ b/cpp/2203/220301-CN.cpp @@ -0,0 +1,68 @@ +#include +#include + +/** + * 6. Zigzag Conversion + * 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 s, int numRows); + */ + +class Solution { +public: + static std::string convert(const std::string& s, int numRows) { + int n = s.length(); + if (n == 1 || numRows == 1) + return s; + + int interval = (numRows << 1) - 2; + int spaceH = interval - numRows; + + std::string ret; + // Line 0 + for (int i = 0; i < n; i += interval) { + // if (i) + // ret += std::string(spaceH, ' '); + ret.push_back(s[i]); + } + // ret.push_back('\n'); + + // Line [1, n) + for (int i = 1; i < numRows - 1; ++i) { + for (int j = i; j < n; j += interval) { + ret.push_back(s[j]); + + // Check if this group's counterpart is OK. + int cp = (interval - j % interval) + (j / interval * interval); + if (cp < n) { + // int spaceL = cp % interval - numRows; + // int spaceR = spaceH - spaceL - 1; + // ret += std::string(spaceL, ' '); + ret.push_back(s[cp]); + // if (spaceR && cp / interval * interval + interval + j % interval < n) + // ret += std::string(spaceR, ' '); + } + } + // ret.push_back('\n'); + } + + // Line n + for (int i = numRows - 1; i < n; i += interval) { + // if (i / interval) + // ret += std::string(spaceH, ' '); + ret.push_back(s[i]); + } + return ret; + } +}; + +int main() { + std::cout << Solution::convert("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 6); + return 0; +} diff --git a/cpp/2203/CMakeLists.txt b/cpp/2203/CMakeLists.txt new file mode 100644 index 0000000..a5667fb --- /dev/null +++ b/cpp/2203/CMakeLists.txt @@ -0,0 +1,6 @@ +CMAKE_MINIMUM_REQUIRED(VERSION 3.21) +PROJECT(2203) + +SET(CMAKE_CXX_STANDARD 23) + +ADD_EXECUTABLE(2203 220301-CN.cpp) diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index 93c3ada..a674ca3 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -9,6 +9,7 @@ SET(CMAKE_CXX_FLAGS "-Wall") ADD_EXECUTABLE(leetcode-cpp main.cpp) # ADD_SUBDIRECTORY(2112) -ADD_SUBDIRECTORY(2201) -ADD_SUBDIRECTORY(2202) +# ADD_SUBDIRECTORY(2201) +# ADD_SUBDIRECTORY(2202) +ADD_SUBDIRECTORY(2203) ADD_SUBDIRECTORY(more)