首頁 > 後端開發 > 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 '?' 是 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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板