s0038
This commit is contained in:
parent
9a6595462d
commit
8ce5ca9166
14
include/s0038_count_and_say.hpp
Normal file
14
include/s0038_count_and_say.hpp
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
#ifndef S0038_COUNT_AND_SAY_HPP
|
||||||
|
#define S0038_COUNT_AND_SAY_HPP
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
#include <algorithm>
|
||||||
|
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
string countAndSay(int n);
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif
|
21
src/s0038_count_and_say.cpp
Normal file
21
src/s0038_count_and_say.cpp
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
#include "s0038_count_and_say.hpp"
|
||||||
|
|
||||||
|
string Solution::countAndSay(int n) {
|
||||||
|
if (n == 1) {
|
||||||
|
return "1";
|
||||||
|
} else if (n <= 0) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
string prev = countAndSay(n - 1);
|
||||||
|
string result{""};
|
||||||
|
int len = prev.length();
|
||||||
|
int pos{0}, start{0};
|
||||||
|
while (pos < len) {
|
||||||
|
while (pos < len && prev[pos] == prev[start]) {
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
result += to_string(pos - start) + prev[start];
|
||||||
|
start = pos;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
17
tests/s0038_count_and_say.cpp
Normal file
17
tests/s0038_count_and_say.cpp
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
#include "s0038_count_and_say.hpp"
|
||||||
|
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
|
TEST(Problem38, Case1) {
|
||||||
|
int i{1};
|
||||||
|
string o{"1"};
|
||||||
|
Solution solution;
|
||||||
|
EXPECT_EQ(solution.countAndSay(i), o);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Problem38, Case2) {
|
||||||
|
int i{4};
|
||||||
|
string o{"1211"};
|
||||||
|
Solution solution;
|
||||||
|
EXPECT_EQ(solution.countAndSay(i), o);
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user