Skip to content

Commit

Permalink
Added Decode String
Browse files Browse the repository at this point in the history
  • Loading branch information
Ace-Krypton committed Oct 1, 2023
1 parent 1829d11 commit dde2cdc
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 0 deletions.
11 changes: 11 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1206,4 +1206,15 @@ add_executable(AsteroidCollision
target_link_libraries(
AsteroidCollision
GTest::gtest_main
)

# Decode String
add_executable(DecodeString
Medium/DecodeString/include/solution.hpp
Medium/DecodeString/tests/test.cpp
)

target_link_libraries(
DecodeString
GTest::gtest_main
)
39 changes: 39 additions & 0 deletions Medium/DecodeString/include/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#pragma once

#include <stack>
#include <vector>
#include <iostream>
#include <algorithm>
#include <gtest/gtest.h>

class Solution {
public:
static auto decode_string(const std::string &word) -> std::string {
std::stack<std::string> substrings;
std::stack<size_t> multipliers;
size_t multiplier = 0;
std::string current_sub;

for (const char &ch : word) {
if (isdigit(ch)) {
multiplier = multiplier * 10 + (ch - '0');
} else if (ch == '[') {
multipliers.push(multiplier);
substrings.push(current_sub);
multiplier = 0;
current_sub.clear();
} else if (ch == ']') {
size_t repeat_count = multipliers.top();
multipliers.pop();
std::string previous_sub = substrings.top();
substrings.pop();
for (size_t i = 0; i < repeat_count; ++i) {
previous_sub += current_sub;
}
current_sub = previous_sub;
} else current_sub += ch;
}

return current_sub;
}
};
38 changes: 38 additions & 0 deletions Medium/DecodeString/tests/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#include "../include/solution.hpp"

class DecodeString : public ::testing::Test {
protected:
~DecodeString() override = default;
};

TEST_F(DecodeString, FirstTest) {
std::string word = "3[a]2[bc]";

std::string result = Solution::decode_string(word);

std::string expected = "aaabcbc";
ASSERT_EQ(result, expected);
}

TEST_F(DecodeString, SecondTest) {
std::string word = "3[a2[c]]";

std::string result = Solution::decode_string(word);

std::string expected = "accaccacc";
ASSERT_EQ(result, expected);
}

TEST_F(DecodeString, ThirdTest) {
std::string word = "2[abc]3[cd]ef";

std::string result = Solution::decode_string(word);

std::string expected = "abcabccdcdcdef";
ASSERT_EQ(result, expected);
}

auto main(int argc, char **argv) -> int {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

0 comments on commit dde2cdc

Please sign in to comment.