c++ - 为什么我的 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
解决方案
如果你使用函数来解决这个问题,对你来说会容易得多。
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 '?'
}
}
}
}
推荐阅读
- c# - 通用存储库模式中的主键属性名称不同
- python - Python - 如何将 Unicode 代码点转换为字符
- algorithm - 拓扑排序,受节点的“值”约束?
- json - 从跨外键的 Django 模型创建 JSON 数据
- spring - 如何在intellij中删除标记为库根的文件夹?
- mysql - MySQL join:即使第二个表没有匹配的数据,如何从一个表中获取结果
- android - 在片段中隐藏键盘屏幕
- php - Laravel 5.3 foreach 来自 2 个不同模型的 2 个集合
- swift - Swift4 中的 RxCocoa 映射可选错误,带有“无法转换类型“字符串?”的值
- ruby-on-rails - Rails 链接到显示以外的其他视图