DSA自学课程:最多为 K 的字典上最短的字符串,它不是给定字符串的子字符串

102 阅读3分钟

词汇学上最短的字符串,其长度最多为K,并且不是给定字符串的子串。

  • 最后更新 : 2021年8月5日

给定一个字符串 S,任务是找出长度小于或等于K的词典上最短的字符串,该字符串不是给定字符串子串。如果不可能,则打印-1。

例子。

输入。 S = zxabcehgf, K = 2
**输出:**d
说明。 从词法上看, 不属于给定字符串的子串的最短字符串是d。

输入。 S = sdhaacbdefghijklmnopqrstuvwxyz, K = 3
**输出:**ab

办法。这 个问题可以通过寻找给定字符串 S的所有长度小于或等于K的子串来解决。然后从词典上最小的字符串'a'开始,不断形成下一个字符串,直到我们找不到答案。按照下面的步骤来解决这个问题。

  • 初始化一组 字符串,例如st, 以存储所有长度最多为K子字符串
  • 1K 进行迭代,创建所有可能长度为1K的字符串。
  • 检查当前形成的字符串是否存在于这个集合中。如果没有,则打印出来并返回。
  • 否则,形成下一个lexicographical字符串,重复这一过程,直到找到答案

下面是上述方法的实现。

C++

// C++ implementation for above approach
#include <bits/stdc++.h>
using namespace std;
// Function to return a set of all
// substrings of given string which have
// length less than or equal to k
set<string> presentSubstring(string s,int k)
{
set<string> st;
int n = s.length();
for (int i = 0; i < n; i++) {
string s1 ="";
for (int j = 0; j < k && i + j < n; j++) {
s1.push_back(s[i + j]);
st.insert(s1);
}
}
return st;
}
// Function to print the lexicographically
// smallest substring of length atmost k
// which is not present in given string s
string smallestSubstring(string s,int k)
{
set<string> st;
// All substrings of length atmost k
// present in string s are stored in
// this set
st = presentSubstring(s, k);
int index;
// Loop to change length of substring
for (int len = 1; len <= k; len++) {
// String with length=len which has
// all characters as 'a'
string t(len,'a');
while (true) {
// If the substrings set does
// not contain this string then
// we have found the answer
if (st.count(t) == 0) {
return t;
}
index = len - 1;
// Changing the likes of 'azz'
// and 'daz' to 'baa' and 'dba'
// respectively
while (index >= 0 && t[index] =='z') {
t[index] ='a';
index--;
}
if (index >= 0)
t[index]++;
// Reached a string like 'zz'
// or 'zzz' increase the length
// of the substring
else
break;
}
}
return "-1";
}
// Driver Code
int main()
{
// Given Input
string s ="sdhaacbdefghijklmnopqrstuvwxyz";
int K = 3;
// Function Call
cout << smallestSubstring(s, K) << endl;
return 0;
}

输出

ab

**时间复杂度。**O(K*N)
辅助空间。O(K*N)

读者请注意!现在不要停止学习。以学生可接受的价格掌握所有重要的DSA概念。 DSA自学课程以适合学生的价格掌握所有重要的DSA概念,并为行业做好准备。 要完成从学习语言到DS Algo以及更多的准备工作,请参考 完整的面试准备课程.

如果你想参加专家的现场课程 ,请参考 面向在职人士的DSA现场课程面向学生的竞争性编程直播课程.

我的个人笔记 箭头_下降_上升

保存