找到兩個具有一個最小子字串的子字串的 C++ 程式碼
假設我們有一個包含 n 個字元的小寫字串 S。我們需要找到兩個非空子字串 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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP