Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions hide-secret.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#include <vector>

void hide_secret(char* const text, const char* const secret) {
if (text == nullptr || secret == nullptr){
return;
}

int m = 0;
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Переменным лучше давать более осмысленные имена. В продакшн коде однобуквенные названия — моветон (у математиков и научных сотрудников только так принято)

const char* temp = secret;
while (*temp != '\0') {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Для определения длины строки можно воспользоваться std::strlen. Она примерно то же самое делает

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот этот цикл можно было организовать проще (если не заменять на std::strlen):

int m = 0;
for (; secret[m] != '\0'; ++m) {}

Исчезла необходимость в переменной temp и снизилась когнитивная нагрузка кода

m++;
temp++;
}

if (m == 0) {
return;
}

std::vector<int> lps(m);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут тоже лучше другое имя придумать. Понятно, что можно разобраться в назначении объекта, прочитав код дальше, но гораздо лучше, когда все сразу понятно в момент объявления объекта.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я понял, почему вы такие имена выбрали) У вас алгоритм Кнута-Морриса-Пратта.


int len = 0;
lps[0] = 0;
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поторопились вектор использовать, мы его еще не проходили) Если ваш код запустить, то получим обращение к неинициализированной памяти.

Оператор [] не выделяет память для новых элементов. Раз уж начали использовать вектор, то советую ознакомиться:

  1. https://en.cppreference.com/w/cpp/container/vector.html
  2. https://en.cppreference.com/w/cpp/container/vector/push_back.html
  3. https://en.cppreference.com/w/cpp/container/vector/resize.html

Но вообще задание решается спокойно и без динамической памяти.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Проглядел передачу размера в вектор. Нет обращения к неициализированной памяти, ошибся


int i = 1;
while (i < m) {
if (secret[i] == secret[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}

int j = 0;
i = 0;

while (text[i] != '\0') {
if (secret[j] == text[i]) {
j++;
i++;
}

if (j == m) {
for (int k = i - j; k < i; k++) {
text[k] = 'x';
}
j = lps[j - 1];
} else if (text[i] != '\0' && secret[j] != text[i]) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
}