首页 > 后端开发 > C++ > 正文

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

PHPz
发布: 2023-09-13 20:41:04
转载
498 人浏览过

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

在本文中,我们将深入探讨字符串操作领域中一个有趣的问题:如何通过替换“?”字符来检查给定字符串的字符是否可以变为非递减顺序。这个问题为您提供了一个练习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<bits/stdc++.h>
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 << "Yes, the string can be made non-decreasing by replacing '?'s.\n";
   else
      cout << "No, the string cannot be made non-decreasing by replacing '?'s.\n";
   return 0;
}
登录后复制

Output

No, the string cannot be made non-decreasing by replacing '?'s.
登录后复制

The checkNonDecreasing function takes as input a string s and returns a boolean value indicating whether the characters of the string can be made non-decreasing by replacing '?'s.

In this test case, the input string is "ac?b". The checkNonDecreasing function is called with this string as the argument, and the result is a boolean value that is printed out.

结论

检查字符串中的字符是否可以通过替换“?”来使其非递减是一个考验您对字符串操作和ASCII值的理解的问题。通过练习这样的问题,您可以加强在C++中处理字符串的能力。

以上是检查字符串的字符是否可以通过替换'_'来变得非递减的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板