首頁 >後端開發 >C++ >檢查字串的字元是否可以透過替換'_'來變得非遞減

檢查字串的字元是否可以透過替換'_'來變得非遞減

PHPz
PHPz轉載
2023-09-13 20:41:04506瀏覽

檢查字串的字元是否可以透過替換_來變得非遞減

在本文中,我們將深入探討字串操作領域中一個有趣的問題:如何透過替換「?」字元來檢查給定字串的字元是否可以變為非遞減順序。這個問題為您提供了一個練習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 '?' 是 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刪除