Почему я не получаю желаемый результат для моей проблемы с ++ - PullRequest
0 голосов
/ 17 мая 2019

Я решаю вопрос, который гласит: менять каждое '?' с 'a' в строке, если не содержит, если не будет образовывать последовательные 'a', иначе заменить на 'b', например. a? b будет abb, а не aab, потому что здесь 2 a являются последовательными .

Моя проблема заключается в том, что для i = 3 моя строка должна быть перезаписана с помощью 'b', в соответствии с моим кодом, который она вводит в нужный блок, но строка не записывается с помощью b, но во всех других случаях там, где должно быть написано «а», написано. Помогите мне с этим.

Здесь вы можете обратиться к формулировке проблемы, чтобы лучше понять мою проблему: https://www.hackerearth.com/practice/algorithms/greedy/basics-of-greedy-algorithms/practice-problems/algorithm/exploring-ruins/

#include <iostream>
using namespace std;

int main() {
    string str;
    cin >> str;
    int n = str.size();

    for(int i = 0; i < str.size(); i++) {
        if(str[i] == '?') {
            if(i == 0) {
                if(str[i + 1] == 'a')
                    str[i] = 'b';
                else
                    str[i] = 'a';
                cout << "I am in if" << endl;
            } else if(i == n - 1) {
                if(str[i - 1] == 'a')
                    str[i] == 'b';
                else
                    str[i] == 'a';
                cout << "I am in if of  else if " << endl;
            } else {
                if(str[i + 1] == 'a' || str[i - 1] == 'a') {
                    str[i] == 'b';
                    cout << "I am in if  of  else " << endl;
                } else {
                    str[i] = 'a';
                    cout << "I am in else of else " << endl;
                }
            }
            cout << str[i] << endl;
        } else
            continue;
    }
    cout << str << endl;

    return 0;
}

Заданная строка:? Ba ?? b желаемый результат: ababab мой вывод: aba? ab

1 Ответ

0 голосов
/ 17 мая 2019

Будет намного проще, если вы воспользуетесь функциями для решения этой проблемы.

bool check_neighbors_for_a(const string &str, size_t place) {
    bool result = false;
    if (place > 0) { // If there is a char before the current char
        result = str[place - 1] == 'a'; // If the previous char is 'a' result become true
    }
    if (place < str.size() - 1) { // If there is a char after the current char
        result = result || str[place + 1] == 'a'; // If the result has become true before this line, result will stay true. Else, result will be true if the next char is equal to 'a'.
        // For example: b?a => result = (false || 'a' == 'a')
        // For example: a?b => result = (true  || 'b' == 'a')
        // For example: a?a => result = (true  || 'a' == 'a')
    }
    return result;
}

void replace_questions_by_a(string &str) {
    for (size_t i = 0; i < str.size(); i++) {
        if (str[i] == '?') {
            if (check_neighbors_for_a(str, i)) { // If one of the neighbors is equal to 'a'
                str[i] = 'b'; // Place 'b' instead of '?'
            } else {
                str[i] = 'a'; // Place 'a' instead of '?'
            }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...