检查字符串的字符是否可以通过替换’_’来变得非递减

2023年 9月 13日 29.0k 0

检查字符串的字符是否可以通过替换'_'来变得非递减

在本文中,我们将深入探讨字符串操作领域中一个有趣的问题:如何通过替换“?”字符来检查给定字符串的字符是否可以变为非递减顺序。这个问题为您提供了一个练习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

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论