From af4bb9619781d5adcb03399a30abc0635b8c7ce3 Mon Sep 17 00:00:00 2001 From: RAJ VARDHAN CHAUDHARY <112545110+rajchaudhary99@users.noreply.github.com> Date: Tue, 1 Oct 2024 17:17:00 +0530 Subject: [PATCH] Create ZigzagConversion.cpp --- ZigzagConversion.cpp | 47 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 ZigzagConversion.cpp diff --git a/ZigzagConversion.cpp b/ZigzagConversion.cpp new file mode 100644 index 0000000..21d2beb --- /dev/null +++ b/ZigzagConversion.cpp @@ -0,0 +1,47 @@ +#include +#include +#include + +using namespace std; + +class Solution { +public: + string convert(string s, int numRows) { + if (numRows == 1 || numRows >= s.size()) return s; + + string ans; + vector> rows(numRows); + int k = 0; + int direction = -1; + + for (const char c : s) { + rows[k].push_back(c); + if (k == 0 || k == numRows - 1) + direction *= -1; + k += direction; + } + + for (const vector& row : rows) + for (const char c : row) + ans += c; + + return ans; + } +}; + +int main() { + Solution solution; + string input; + int numRows; + + // Example input + cout << "Enter a string: "; + getline(cin, input); + cout << "Enter the number of rows: "; + cin >> numRows; + + string result = solution.convert(input, numRows); + cout << "Converted string: " << result << endl; + + return 0; +}