在本文中,我们将深入探讨字符串操作领域中一个有趣的问题:如何通过替换“?”字符来检查给定字符串的字符是否可以变为非递减顺序。这个问题为您提供了一个练习C++中字符串操作和条件检查技巧的绝佳机会。
Problem Statement
Given a string consisting of alphabetic characters and question marks (?), determine whether the characters can be made non-decreasing by replacing the '?'s.
The non-decreasing condition means that for every two adjacent characters in the string, the ASCII value of the second character is not less than the ASCII value of the first one.
方法
我们将使用一种简单的方法来解决这个问题 −
-
Iterate through the string from left to right.
-
If a '?' is encountered, replace it with the character that came before it (unless it's the first character, in which case replace it with 'a').
-
Finally, check if the resultant string is non-decreasing.
Example
#include
using namespace std;
bool checkNonDecreasing(string s) {
int n = s.size();
if (s[0] == '?') s[0] = 'a';
for (int i = 1; i < n; i++) {
if (s[i] == '?') s[i] = s[i-1];
if (s[i] < s[i-1]) return false;
}
return true;
}
int main() {
string s = "ac?b";
bool result = checkNonDecreasing(s);
if(result)
cout