找到两个具有一个最小子字符串的子字符串的 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