📌  相关文章
📜  从给定的字符串中查找仅由元音组成的唯一子字符串

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

从给定的字符串中查找仅由元音组成的唯一子字符串

给定大小为N的字符串str ,由大写和小写英文字母组成。任务是找到所有仅包含元音的唯一子串。

例子:

朴素方法:最简单的方法是生成所有子字符串并检查它们中的每一个是否仅包含元音以及它们是否唯一。使用以下步骤:

  • 生成字符串的所有子字符串。
  • 使用map来跟踪唯一的子字符串。
  • 如果子字符串仅包含元音并且不在地图上,则将其添加到地图并将其存储为答案。
  • 打印所有答案

下面是上述方法的实现:

C++
// C++ code to implement the above approach
#include 
using namespace std;
 
// Function to check if a character is vowel
bool isvowel(char ch)
{
    return (ch == 'a' or ch == 'A' or
            ch == 'e' or ch == 'E'
            or ch == 'i' or ch == 'I'
            or ch == 'o' or ch == 'O' or
            ch == 'u' or ch == 'U');
}
 
// Function to check whether
// string contains only vowel
bool isvalid(string& s)
{
    int n = s.length();
 
    for (int i = 0; i < n; i++) {
         
        // Check if the character is
        // not vowel then invalid
        if (!isvowel(s[i]))
            return false;
    }
 
    return true;
}
 
// Function for generating
// all unique substrings of only vowels.
void generateVowelSubstrings(string params)
{
    int ans = 0;
    unordered_map map;
     
    // Generate all substring of string
    for (int i = 0; i < params.length();
         i++) {
        string temp = "";
        for (int j = i; j < params.length();
             j++) {
            temp += params[j];
             
            // If temp contains only vowels
            if (isvalid(temp)) {
                map[temp] = true;
            }
        }
    }
     
    unordered_map::iterator itr;
    for (itr = map.begin(); itr != map.end();
         ++itr) {
         
        // Printing all unique substrings.
        cout << itr->first << '\n';
    }
}
 
// Driver code
int main()
{
    string str = "GeeksForGeeks";
    generateVowelSubstrings(str);
    return 0;
}


Java
/*package whatever //do not write package name here */
// Java code to implement the above approach
import java.io.*;
import java.util.*;
 
class GFG {
    // Function to check if a character is vowel
    public static boolean isVowel(char ch)
    {
        return (ch == 'a' || ch == 'A' || ch == 'e'
                || ch == 'E' || ch == 'i' || ch == 'I'
                || ch == 'o' || ch == 'O' || ch == 'u'
                || ch == 'U');
    }
    // Function to check whether
    // string contains only vowel
    public static boolean isValid(String s)
    {
        int n = s.length();
        for (int i = 0; i < n; i++) {
            // Check if the character is
            // not vowel then invalid
            if (!isVowel(s.charAt(i)))
                return false;
        }
        return true;
    }
 
    // Function for generating unique substrings of vowels.
    public static void
    generateVowelSubstrings(String string)
    {
        int ans = 0;
        HashMap map = new HashMap<>();
        // Generate all subString of s
        for (int i = 0; i < string.length(); i++) {
            String temp = "";
            for (int j = i; j < string.length(); j++)
            {
                temp += string.charAt(j);
               
                // If temp contains only vowels
                if (isValid(temp))
                {
                   
                    // store it only if substring is absent
                    // in map.
                    map.putIfAbsent(temp, true);
                }
            }
        }
        for (String key : map.keySet())
        {
           
            // printing all unique substring.
            System.out.println(key);
        }
    }
    // Driver Code
    public static void main(String[] args)
    {
        String str = "GeeksForGeeks";
        generateVowelSubstrings(str);
    }
}
 
// This code is contributed by kaalel.


Python3
# JavaScript code to implement above approach
 
# Function to check if a character is vowel
def isVowel(c):
     
        # Checking for vowels.
    return ((c == "a") or (c == "A") or
            (c == "e") or (c == "E") or
            (c == "i") or (c == "I") or
            (c == "o") or (c == "O") or
            (c == "u") or (c == "U"))
 
# Extracting all the maximum length
# sub-strings that contain only vowels.
def vowelSubstrings(params):
    str = ""
 
    # Using map to remove identicals
    # substrings. e.g. AiotrfAio has 2 "Aio".
    map = {}
    for i in range(len(params)):
        subString = params[i: i + 1]
        if(isVowel(subString)):
                str += subString
        else:
            # Storing a substring only if
            # it is not empty.
            if len(str) != 0:
                map[str] = True
                str = ""
    if (len(str) != 0):
        map[str] = True
    return map
 
    # Function to generate all unique substrings
    # containing only vowels
def generateVowelSubstrings(params):
 
    substringMap = vowelSubstrings(params)
    map = {}
         
        # map iterator.
    for itr in substringMap:
        x = itr
 
        # For each substring stored in map
        # generate all possible substrings.
        for i in range(len(x)):
            for l in range(1,len(x) - i+1):
                # Storing the generated
                # substring if it is
                # absent in the map.
                map[x[i:i + l]] = True
 
    for itr in map:
         
        # Printing all values in map.
        print(itr)
 
# Driver code
str = "GeeksForGeeks"
generateVowelSubstrings(str)
 
# This code is contributed by shinjanpatra


C#
/*package whatever //do not write package name here */
// C# code to implement the above approach
using System;
using System.Collections.Generic;
class GFG
{
   
    // Function to check if a character is vowel
    public static bool isVowel(char ch)
    {
        return (ch == 'a' || ch == 'A' || ch == 'e'
                || ch == 'E' || ch == 'i' || ch == 'I'
                || ch == 'o' || ch == 'O' || ch == 'u'
                || ch == 'U');
    }
    // Function to check whether
    // string contains only vowel
    public static bool isValid(string s)
    {
        int n = s.Length;
        for (int i = 0; i < n; i++) {
            // Check if the character is
            // not vowel then invalid
            if (!isVowel(s[i]))
                return false;
        }
        return true;
    }
 
    // Function for generating unique substrings of vowels.
    public static void generateVowelSubstrings(string str)
    {
 
        Dictionary map
            = new Dictionary();
        // Generate all subString of s
        for (int i = 0; i < str.Length; i++) {
            string temp = "";
            for (int j = i; j < str.Length; j++) {
                temp += str[j];
 
                // If temp contains only vowels
                if (isValid(temp)) {
 
                    // store it only if substring is absent
                    // in map.
                    if (!map.ContainsKey(temp))
                        map[temp] = true;
                }
            }
        }
        foreach(KeyValuePair i in map)
        {
 
            // printing all unique substring.
            Console.WriteLine(i.Key);
        }
    }
   
    // Driver Code
    public static void Main(string[] args)
    {
        string str = "GeeksForGeeks";
        generateVowelSubstrings(str);
    }
}
 
// This code is contributed by ukasp.


Javascript


C++
// C++ code to implement above approach
#include 
using namespace std;
 
// Function to check if a character is vowel
bool isVowel(string c)
{
    // Checking for vowels.
    return ((c == "a") || (c == "A") ||
            (c == "e") || (c == "E") ||
            (c == "i") || (c == "I") ||
            (c == "o") || (c == "O") ||
            (c == "u") || (c == "U"));
}
 
// Extracting all the maximum length
// sub-strings that contain only vowels.
unordered_map vowelSubstrings(
    string params)
{
    string str;
     
    // Using map to remove identicals
    // substrings. e.g. AiotrfAio has 2 "Aio".
    unordered_map map;
    for (int i = 0; i < params.length();
         i++) {
        string subString = params.substr(i, 1);
        if (isVowel(subString)) {
            str += subString;
        }
        else {
             
            // Storing a substring only if
            // it is not empty.
            if (!str.empty())
                map[str] = true;
            str = "";
        }
    }
    if (!str.empty())
        map[str] = true;
    return map;
}
 
// Function to generate all unique substrings
// containing only vowels
void generateVowelSubstrings(string params)
{
    unordered_map substringMap
        = vowelSubstrings(params);
    unordered_map map;
    // map iterator.
    unordered_map::iterator itr;
    for (itr = substringMap.begin();
         itr != substringMap.end(); ++itr) {
        string x = itr->first;
         
        // For each substring stored in map
        // generate all possible substrings.
        for (int i = 0; i < x.length(); i++) {
            for (int len = 1; len <=
                 x.length() - i; len++)
            {
                // Storing the generated
                // substring if it is
                // absent in the map.
                map[x.substr(i, len)] = true;
            }
        }
    }
    for (itr = map.begin(); itr != map.end();
         ++itr) {
        // Printing all values in map.
        cout << itr->first << '\n';
    }
}
 
// Driver code
int main()
{
    string str = "GeeksForGeeks";
    generateVowelSubstrings(str);
    return 0;
}


Java
/*package whatever //do not write package name here */
// Java code to implement above approach
import java.io.*;
import java.util.*;
 
class GFG {
    // Function to check if a character is vowel
    public static boolean isVowel(String c)
    {
        // checking for vowels.
        return (c.equals("a") || c.equals("A")
                || c.equals("e") || c.equals("E")
                || c.equals("i") || c.equals("I")
                || c.equals("o") || c.equals("O")
                || c.equals("u") || c.equals("U"));
    }
 
    // extracting all the maximum length sub-strings that
    // contain only vowels.
    public static HashMap
    VowelSubstrings(String string)
    {
        String str = "";
        // using map to remove identicals substrings. Ex :-
        // AiotrfAiopdvge(it has 2 "Aio").
        HashMap map = new HashMap<>();
        for (int i = 0; i < string.length(); i++) {
            String subStr = string.substring(i, (i + 1));
            if (isVowel(subStr)) {
                str += subStr;
            }
            else {
                // storing a substring only if it is
                // present.
                if (!str.isEmpty())
                    map.putIfAbsent(str, true);
                str = "";
            }
        }
        if (!str.isEmpty())
            map.putIfAbsent(str, true);
        return map;
    }
    // Function to generate all unique substrings
    // containing only vowels
    public static void
    generateVowelSubstrings(String string)
    {
        HashMap substringMap
            = VowelSubstrings(string);
        HashMap map = new HashMap<>();
        for (String key : substringMap.keySet()) {
            // for each key(substring) stored in map, we
            // generate all possible substrings.
            for (int i = 0; i < key.length(); i++) {
                for (int j = i + 1; j <= key.length();
                     j++) {
                    // storing the generated substring if it
                    // is absent in the map.
                    map.putIfAbsent(key.substring(i, j),
                                    true);
                }
            }
        }
        for (String key : map.keySet()) {
            // printing all values in map.
            System.out.println(key);
        }
    }
    // Driver Code
    public static void main(String[] args)
    {
        String str = "GeeksForGeeks";
        generateVowelSubstrings(str);
    }
}


Python3
# Python code to implement above approach
 
# Function to check if a character is vowel
def isVowel(c):
   
    # Checking for vowels.
    return ((c == "a") or (c == "A") or
            (c == "e") or (c == "E") or
            (c == "i") or (c == "I") or
            (c == "o") or (c == "O") or
            (c == "u") or (c == "U"))
 
# Extracting all the maximum length
# sub-Strings that contain only vowels.
def vowelSubStrings(params):
    Str = ""
     
    # Using map to remove identicals
    # subStrings. e.g. AiotrfAio has 2 "Aio".
    map = dict()
    for i in range(len(params)):
        subString = params[i:i + 1]
        if (isVowel(subString)):
            Str += subString
        else:
             
            # Storing a subString only if
            # it is not empty.
            if (len(Str) > 0):
                map[Str] = True
            Str = ""
 
    if (len(Str) > 0):
        map[Str] = True
    return map
 
# Function to generate all unique subStrings
# containing only vowels
def generateVowelSubStrings(params):
 
    subStringMap = vowelSubStrings(params)
    map = dict()
    # map iterator.
    for [key,val] in subStringMap.items():
        x = key
         
        # For each subString stored in map
        # generate all possible subStrings.
        for i in range(len(x)):
            for Len in range(1,len(x) - i + 1):
               
                # Storing the generated
                # subString if it is
                # absent in the map.
                map[x[i: i+Len]] = True
    for [key,val] in map.items():
       
        # Printing all values in map.
        print(key)
 
# Driver code
Str = "GeeksForGeeks"
generateVowelSubStrings(Str)
 
# This code is contributed by shinjanpatra


C#
/*package whatever //do not write package name here */
// C# code to implement the above approach
using System;
using System.Collections.Generic;
public class GFG
{
 
  // Function to check if a character is vowel
  public static bool isVowel(char ch)
  {
    return (ch == 'a' || ch == 'A' || ch == 'e'
            || ch == 'E' || ch == 'i' || ch == 'I'
            || ch == 'o' || ch == 'O' || ch == 'u'
            || ch == 'U');
  }
   
  // Function to check whether
  // string contains only vowel
  public static bool isValid(string s)
  {
    int n = s.Length;
    for (int i = 0; i < n; i++)
    {
       
      // Check if the character is
      // not vowel then invalid
      if (!isVowel(s[i]))
        return false;
    }
    return true;
  }
 
  // Function for generating unique substrings of vowels.
  public static void generateVowelSubstrings(string str)
  {
 
    Dictionary map
      = new Dictionary();
     
    // Generate all subString of s
    for (int i = 0; i < str.Length; i++) {
      string temp = "";
      for (int j = i; j < str.Length; j++) {
        temp += str[j];
 
        // If temp contains only vowels
        if (isValid(temp)) {
 
          // store it only if substring is absent
          // in map.
          if (!map.ContainsKey(temp))
            map[temp] = true;
        }
      }
    }
    foreach(String i in map.Keys)
    {
 
      // printing all unique substring.
      Console.WriteLine(i);
    }
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
    string str = "GeeksForGeeks";
    generateVowelSubstrings(str);
  }
}
 
// This code is contributed by gauravrajput1


Javascript


输出
o
e
ee

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

有效方法:解决这个问题的更好方法是提取所有仅包含元音的最大长度子串。现在分别针对所有这些子字符串,在地图的帮助下生成仅包含元音的唯一子字符串。请按照以下步骤操作:

  • 存储所有仅包含元音的最大长度子串(例如,对于“Geeksaioer”,最大长度之一是“ee”和“aioe”)。
  • 使用这些子串并从这些子串中生成较小的段,并使用映射来查找唯一的段。
  • 打印所有唯一的字符串。

下面是上述方法的实现:  

C++

// C++ code to implement above approach
#include 
using namespace std;
 
// Function to check if a character is vowel
bool isVowel(string c)
{
    // Checking for vowels.
    return ((c == "a") || (c == "A") ||
            (c == "e") || (c == "E") ||
            (c == "i") || (c == "I") ||
            (c == "o") || (c == "O") ||
            (c == "u") || (c == "U"));
}
 
// Extracting all the maximum length
// sub-strings that contain only vowels.
unordered_map vowelSubstrings(
    string params)
{
    string str;
     
    // Using map to remove identicals
    // substrings. e.g. AiotrfAio has 2 "Aio".
    unordered_map map;
    for (int i = 0; i < params.length();
         i++) {
        string subString = params.substr(i, 1);
        if (isVowel(subString)) {
            str += subString;
        }
        else {
             
            // Storing a substring only if
            // it is not empty.
            if (!str.empty())
                map[str] = true;
            str = "";
        }
    }
    if (!str.empty())
        map[str] = true;
    return map;
}
 
// Function to generate all unique substrings
// containing only vowels
void generateVowelSubstrings(string params)
{
    unordered_map substringMap
        = vowelSubstrings(params);
    unordered_map map;
    // map iterator.
    unordered_map::iterator itr;
    for (itr = substringMap.begin();
         itr != substringMap.end(); ++itr) {
        string x = itr->first;
         
        // For each substring stored in map
        // generate all possible substrings.
        for (int i = 0; i < x.length(); i++) {
            for (int len = 1; len <=
                 x.length() - i; len++)
            {
                // Storing the generated
                // substring if it is
                // absent in the map.
                map[x.substr(i, len)] = true;
            }
        }
    }
    for (itr = map.begin(); itr != map.end();
         ++itr) {
        // Printing all values in map.
        cout << itr->first << '\n';
    }
}
 
// Driver code
int main()
{
    string str = "GeeksForGeeks";
    generateVowelSubstrings(str);
    return 0;
}

Java

/*package whatever //do not write package name here */
// Java code to implement above approach
import java.io.*;
import java.util.*;
 
class GFG {
    // Function to check if a character is vowel
    public static boolean isVowel(String c)
    {
        // checking for vowels.
        return (c.equals("a") || c.equals("A")
                || c.equals("e") || c.equals("E")
                || c.equals("i") || c.equals("I")
                || c.equals("o") || c.equals("O")
                || c.equals("u") || c.equals("U"));
    }
 
    // extracting all the maximum length sub-strings that
    // contain only vowels.
    public static HashMap
    VowelSubstrings(String string)
    {
        String str = "";
        // using map to remove identicals substrings. Ex :-
        // AiotrfAiopdvge(it has 2 "Aio").
        HashMap map = new HashMap<>();
        for (int i = 0; i < string.length(); i++) {
            String subStr = string.substring(i, (i + 1));
            if (isVowel(subStr)) {
                str += subStr;
            }
            else {
                // storing a substring only if it is
                // present.
                if (!str.isEmpty())
                    map.putIfAbsent(str, true);
                str = "";
            }
        }
        if (!str.isEmpty())
            map.putIfAbsent(str, true);
        return map;
    }
    // Function to generate all unique substrings
    // containing only vowels
    public static void
    generateVowelSubstrings(String string)
    {
        HashMap substringMap
            = VowelSubstrings(string);
        HashMap map = new HashMap<>();
        for (String key : substringMap.keySet()) {
            // for each key(substring) stored in map, we
            // generate all possible substrings.
            for (int i = 0; i < key.length(); i++) {
                for (int j = i + 1; j <= key.length();
                     j++) {
                    // storing the generated substring if it
                    // is absent in the map.
                    map.putIfAbsent(key.substring(i, j),
                                    true);
                }
            }
        }
        for (String key : map.keySet()) {
            // printing all values in map.
            System.out.println(key);
        }
    }
    // Driver Code
    public static void main(String[] args)
    {
        String str = "GeeksForGeeks";
        generateVowelSubstrings(str);
    }
}

Python3

# Python code to implement above approach
 
# Function to check if a character is vowel
def isVowel(c):
   
    # Checking for vowels.
    return ((c == "a") or (c == "A") or
            (c == "e") or (c == "E") or
            (c == "i") or (c == "I") or
            (c == "o") or (c == "O") or
            (c == "u") or (c == "U"))
 
# Extracting all the maximum length
# sub-Strings that contain only vowels.
def vowelSubStrings(params):
    Str = ""
     
    # Using map to remove identicals
    # subStrings. e.g. AiotrfAio has 2 "Aio".
    map = dict()
    for i in range(len(params)):
        subString = params[i:i + 1]
        if (isVowel(subString)):
            Str += subString
        else:
             
            # Storing a subString only if
            # it is not empty.
            if (len(Str) > 0):
                map[Str] = True
            Str = ""
 
    if (len(Str) > 0):
        map[Str] = True
    return map
 
# Function to generate all unique subStrings
# containing only vowels
def generateVowelSubStrings(params):
 
    subStringMap = vowelSubStrings(params)
    map = dict()
    # map iterator.
    for [key,val] in subStringMap.items():
        x = key
         
        # For each subString stored in map
        # generate all possible subStrings.
        for i in range(len(x)):
            for Len in range(1,len(x) - i + 1):
               
                # Storing the generated
                # subString if it is
                # absent in the map.
                map[x[i: i+Len]] = True
    for [key,val] in map.items():
       
        # Printing all values in map.
        print(key)
 
# Driver code
Str = "GeeksForGeeks"
generateVowelSubStrings(Str)
 
# This code is contributed by shinjanpatra

C#

/*package whatever //do not write package name here */
// C# code to implement the above approach
using System;
using System.Collections.Generic;
public class GFG
{
 
  // Function to check if a character is vowel
  public static bool isVowel(char ch)
  {
    return (ch == 'a' || ch == 'A' || ch == 'e'
            || ch == 'E' || ch == 'i' || ch == 'I'
            || ch == 'o' || ch == 'O' || ch == 'u'
            || ch == 'U');
  }
   
  // Function to check whether
  // string contains only vowel
  public static bool isValid(string s)
  {
    int n = s.Length;
    for (int i = 0; i < n; i++)
    {
       
      // Check if the character is
      // not vowel then invalid
      if (!isVowel(s[i]))
        return false;
    }
    return true;
  }
 
  // Function for generating unique substrings of vowels.
  public static void generateVowelSubstrings(string str)
  {
 
    Dictionary map
      = new Dictionary();
     
    // Generate all subString of s
    for (int i = 0; i < str.Length; i++) {
      string temp = "";
      for (int j = i; j < str.Length; j++) {
        temp += str[j];
 
        // If temp contains only vowels
        if (isValid(temp)) {
 
          // store it only if substring is absent
          // in map.
          if (!map.ContainsKey(temp))
            map[temp] = true;
        }
      }
    }
    foreach(String i in map.Keys)
    {
 
      // printing all unique substring.
      Console.WriteLine(i);
    }
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
    string str = "GeeksForGeeks";
    generateVowelSubstrings(str);
  }
}
 
// This code is contributed by gauravrajput1

Javascript


输出
o
ee
e

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