卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64334本站已运行4115

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

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

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

卓越飞翔博客
上一篇: C++ 给定等差数列的和的比率,计算第M项和第N项的比率
下一篇: 找出在范围内不可被任何数整除的数字,使用C++
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏