首頁  >  文章  >  後端開發  >  C++程式碼來找出具有一個最小子字串的兩個子字串

C++程式碼來找出具有一個最小子字串的兩個子字串

WBOY
WBOY轉載
2023-09-06 14:41:14850瀏覽

C++程式碼來找出具有一個最小子字串的兩個子字串

假設我們有一個小寫字串S,它包含n個字元。我們需要找到兩個非空的 子字串P和Q,使得−

  • P和Q都是S的子序列

  • 對每個索引i,S[i ]屬於P和Q中的一個且僅屬於一個。

  • P盡可能地按字典順序最小。

所以,如果輸入是S = "thelightsaber",那麼輸出將會是10,因為我們需要2個紅色的

筆記本,3個綠色筆記本和5本藍色筆記本。

步驟

為了解決這個問題,我們將按照以下步驟進行:

c := S
sort the array c
a := position of (c[0]) in S
delete c from S
print c[0] and S

範例

讓我們看下面的實作以便更好地理解−

#include <bits/stdc++.h>
using namespace std;
void solve(string S){
   string c = S;
   sort(c.begin(), c.end());
   int a = S.find(c[0]);
   S.erase(S.begin() + a);
   cout << c[0] << ", " << S << endl;
}
int main(){
   string S = "thelightsaber";
   solve(S);
}

輸入

"thelightsaber"

輸出

a, thelightsber

以上是C++程式碼來找出具有一個最小子字串的兩個子字串的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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