为什么我的C 问题没有获得所需的输出



我正在解决一个问题,该问题指出:要更改每个?''在字符串中使用" a"(如果不包含(,如果不会形成连续的"A?b将是ABB而不是AAB,因为这里2 A是连续的

我的问题是i = 3它应该用" a"而努力的地方。

您可以从此处推荐问题语句,以更好地理解我的问题:https://www.hackerearth.com/practice/algorithms/algorithms/greedy/basics-of-greedy-algorithms/practice-problems/algorblems/algorithm/algorithm/algorithm/algorithm/algorithm/algorithm/algorithm/algorithm-废墟/

#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

如果您使用功能解决此问题,对您来说会容易得多。

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 '?'
            }
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新