首頁  >  文章  >  後端開發  >  C++程式檢查字串是否嚴格地按字母順序排列

C++程式檢查字串是否嚴格地按字母順序排列

WBOY
WBOY轉載
2023-09-05 17:01:261255瀏覽

C++程式檢查字串是否嚴格地按字母順序排列

假設我們有一個包含 n 個小寫字母的字串 S。如果字串遵循以下規則,則它是嚴格的字母字串-

  • 將空字串寫入T

  • 然後執行下一步n次;
  • 在第i步,取出拉丁字母表中的第i個小寫字母,並將其插入到 字串 T 的左側或字串 T 的右側(c 是拉丁字母表中的第 i 個字母)。

我們必須檢查 S 是否嚴格是否按字母字串排列。

問題類別

要解決這個問題,我們需要操作字串。程式語言中的字串是 儲存在特定的類似數組的資料類型中的字元流。多種語言 將字串指定為特定資料類型(例如 Java、C 、Python);和其他幾種語言 將字串指定為字元數組(例如 C)。字串在編程中很有用,因為它們 通常是各種應用程式中的首選資料類型,並用作輸入的資料類型 和輸出。有各種字串操作,例如字串搜尋、子字串生成、 字串剝離操作、字串翻譯操作、字串替換操作、字串 反向操作等等。查看下面的連結以了解字串如何 用於 C/C 中。

https://www.tutorialspoint.com/cplusplus/cpp_strings.htm

https://www.tutorialspoint.com/cprogramming/c_strings。 htm

因此,如果我們問題的輸入類似於 S = "ihfcbadeg",那麼輸出將為 True。

步驟

要解決這個問題,我們將遵循以下步驟-

len := size of S
for initialize i := len, when i >= 1, update (decrease i by 1), do:
   if S[l] is the i th character, then:
      (increase l by 1)
   otherwise when S[r] is the ith character, then:
      (decrease r by 1)
   Otherwise
      Come out from the loop
if i is same as 0, then:
   return true
Otherwise
   return false

範例

讓我們看看以下實現,以便更好地理解-

#include <bits/stdc++.h>
using namespace std;
bool solve(string S){
   int len = S.size(), l = 0, r = len - 1, i;
   for (i = len; i >= 1; i--){
      if (S[l] - &#39;a&#39; + 1 == i)
         l++;
      else if (S[r] - &#39;a&#39; + 1 == i)
         r--;
      else
         break;
   }
   if (i == 0)
      return true;
   else
      return false;
}
int main(){
   string S = "ihfcbadeg";
   cout << solve(S) << endl;
}

輸入

"ihfcbadeg"

輸出

1

以上是C++程式檢查字串是否嚴格地按字母順序排列的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除