C++程式:查詢需要重新排列多少字元才能將字串排序


假設我們有一個包含n個字元的字串S。S只包含小寫字母。我們必須選擇一個範圍在0到n之間的數字k,然後從S中選擇k個字元並以任意順序排列它們。在此過程中,其餘字元將保持不變。我們只執行此整個操作一次。我們必須找到k的值,以便S按字母順序排序。

因此,如果輸入類似於S = "acdb",則輸出將為3,因為'a'位於正確的位置,其餘字元應該重新排列。

步驟

為了解決這個問題,我們將遵循以下步驟:

n := size of S
d := S
sort the array d
j := 0
for initialize i := 0, when i < n, update (increase i by 1), do:
   if S[i] is not equal to d[i], then:
      (increase j by 1)
return j

示例

讓我們看看下面的實現,以便更好地理解:

#include <bits/stdc++.h>
using namespace std;

int solve(string S) {
   int n = S.size();
   string d = S;
   sort(d.begin(), d.end());
   int j = 0;
   for (int i = 0; i < n; i++) {
      if (S[i] != d[i])
         j++;
   }
   return j;
}

int main() {
   string S = "acdb";
   cout << solve(S) << endl;
}

輸入

"acdb"

輸出

3

更新於:2022年3月3日

瀏覽量:144

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.