首页 > 解决方案 > 为什么我的 c++ 问题没有得到想要的输出

问题描述

我正在解决一个问题:改变每个“?” 字符串中带有 'a' if 不包含 if 不会形成连续的 'a' 否则替换为 'b',例如。a?b 将是 abb 而不是 aab 因为这里 2 a 是连续的

我的问题是对于 i = 3,我的字符串应该根据我的代码被 'b' 覆盖,它正在进入所需的块,但字符串没有用 b 写入,但在所有其他情况下它应该用“a”写出来。帮我解决这些问题。

您可以参考此处的问题陈述以更好地理解我的问题: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

标签: c++stringif-statementcontrol-flow

解决方案


如果你使用函数来解决这个问题,对你来说会容易得多。

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

推荐阅读