C++ 程式碼來判斷字串是否夠多樣


假設我們有一個包含 n 個小寫字母的字串 S。如果字串中有連續的英語字母並且每個字母只出現一次,則稱它為多樣字串。(字母“a”和“z”不相鄰。)我們必須檢查它是否多樣。

因此,如果輸入為 S = "fced",那麼輸出將為 True。

步驟

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

sort the array S
flag := 1
for initialize i := 1, when i < size of S and flag is non-zero,
update (increase i by 1), do:
   if S[i] - S[i - 1] is not equal to 1, then:
      flag := 0
return (if flag is non-zero, then true, otherwise false)

示例

讓我們看看以下實現以獲得更好的理解 -

#include <bits/stdc++.h>
using namespace std;
bool solve(string S){
   sort(S.begin(), S.end());
   int flag = 1;
   for (int i = 1; i < S.size() && flag; i++)
      if (S[i] - S[i - 1] != 1)
         flag = 0;
   return flag ? true : false;
}
int main(){
   string S = "fced";
   cout << solve(S) << endl;
}

輸入

"fced"

輸出

1

更新日期:2022-03-15

248 次瀏覽

啟動你的 職業

完成課程認證

開始
廣告
© . All rights reserved.