📜  最多为 K 的字典上最短的字符串,它不是给定字符串的子字符串

📅  最后修改于: 2022-05-13 01:57:07.837000             🧑  作者: Mango

最多为 K 的字典上最短的字符串,它不是给定字符串的子字符串

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

例子:

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

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

下面是上述方法的实现。

C++
// C++ implementation for above approach
#include 
using namespace std;
 
// Function to return a set of all
// substrings of given string which have
// length less than or equal to k
set presentSubstring(string s, int k)
{
    set 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 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;
}


Java
// Java implementation for above approach
import java.util.*;
 
class GFG
{
 
// Function to return a set of all
// subStrings of given String which have
// length less than or equal to k
static HashSet presentSubString(String s, int k)
{
    HashSet st = new HashSet();
    int n = s.length();
 
    for (int i = 0; i < n; i++) {
        String s1 = "";
 
        for (int j = 0; j < k && i + j < n; j++) {
            s1 += s.charAt(i + j);
 
            st.add(s1);
        }
    }
 
    return st;
}
 
// Function to print the lexicographically
// smallest subString of length atmost k
// which is not present in given String s
static String smallestSubString(String s, int k)
{
    HashSet st = new HashSet();
 
    // 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 = "";
        for(int i=0;i= 0 && t.charAt(index) == 'z') {
                t=t.substring(0,index)+'a'+t.substring(index+1);
                index--;
            }
             
            if (index >= 0)
                t=t.substring(0,index)+ (char)((t.charAt(index))+1) + t.substring(index+1);
 
            // Reached a String like 'zz'
            // or 'zzz' increase the length
            // of the subString
            else
                break;
        }
    }
    return "-1";
}
 
// Driver Code
public static void main(String[] args)
{
 
    // Given Input
    String s = "sdhaacbdefghijklmnopqrstuvwxyz";
    int K = 3;
 
    // Function Call
    System.out.print(smallestSubString(s, K) +"\n");
}
}
 
// This code is contributed by shikhasingrajput


Python3
# Python 3 implementation for above approach
 
# Function to return a set of all
# substrings of given string which have
# length less than or equal to k
def presentSubstring(s, k):
    st = set()
    n = len(s)
    s = list(s)
 
    for i in range(n):
        s1 = ""
        j = 0
        while(j < k and i + j < n):
            s1 += s[i + j]
 
            st.add(s1)
            j += 1
     
    s = ''.join(s)
    return st
 
# Function to print the lexicographically
# smallest substring of length atmost k
# which is not present in given string s
def smallestSubstring(s, k):
    st = set()
 
    # All substrings of length atmost k
    # present in string s are stored in
    # this set
    st = presentSubstring(s, k)
 
    index = 0
 
    # Loop to change length of substring
    for len1 in range(1,k+1,1):
        # String with length=len which has
        # all characters as 'a'
        t = []
        for x in range(len1):
            t.append('a')
 
        while (True):
            # If the substrings set does
            # not contain this string then
            # we have found the answer
            if (''.join(t) not in st):
                return ''.join(t)
 
            index = len1 - 1
 
            # Changing the likes of 'azz'
            # and 'daz' to 'baa' and 'dba'
            # respectively
            while (index >= 0 and t[index] == 'z'):
                t[index] = 'a'
                index -= 1
 
            if (index >= 0):
                t[index] = chr(ord(t[index])+1)
 
            # Reached a string like 'zz'
            # or 'zzz' increase the length
            # of the substring
            else:
                break
    return "-1"
 
# Driver Code
if __name__ == '__main__':
    # Given Input
    s = "sdhaacbdefghijklmnopqrstuvwxyz"
    K = 3
 
    # Function Call
    print(smallestSubstring(s, K))
     
    # This code is contributed by ipg2016107.


C#
// C# implementation for above approach
using System;
using System.Collections.Generic;
 
class GFG {
 
    // Function to return a set of all
    // substrings of given string which have
    // length less than or equal to k
    static HashSet presentSubstring(string s, int k)
    {
        HashSet st = new HashSet();
        int n = s.Length;
 
        for (int i = 0; i < n; i++) {
            string s1 = "";
 
            for (int j = 0; j < k && i + j < n; j++) {
                s1 += s[i + j];
 
                st.Add(s1);
            }
        }
 
        return st;
    }
 
    // Function to print the lexicographically
    // smallest substring of length atmost k
    // which is not present in given string s
    static string smallestSubstring(string s, int k)
    {
        HashSet st = new HashSet();
 
        // 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 = "";
            for (int i = 0; i < len; i++)
                t += 'a';
 
            while (true) {
 
                // If the substrings set does
                // not contain this string then
                // we have found the answer
                if (st.Contains(t)==false) {
                    return t;
                }
 
                index = len - 1;
 
                // Changing the likes of 'azz'
                // and 'daz' to 'baa' and 'dba'
                // respectively
                while (index >= 0 && t[index] == 'z') {
                    t = t.Substring(0, index) + 'a'
                        + t.Substring(index + 1);
                    index--;
                }
 
                if (index >= 0) {
                    t = t.Substring(0, index)
                        + Convert.ToChar((int)t[index] + 1)
                        + t.Substring(index + 1);
                }
 
                // Reached a string like 'zz'
                // or 'zzz' increase the length
                // of the substring
                else
                    break;
            }
           // t += 'b';
        }
        return "-1";
    }
 
    // Driver Code
    public static void Main()
    {
 
        // Given Input
        string s = "sdhaacbdefghijklmnopqrstuvwxyz";
        int K = 3;
 
        // Function Call
        Console.Write(smallestSubstring(s, K));
    }
}
 
// This code is contributed by ipg2016107.


Javascript


输出
ab

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