给定一个字符串数组arr[] ,任务是找到可以通过连接给定数组的子序列生成的不同字符字符串的最大可能长度。
例子:
Input: arr[] = {“ab”, “cd”, “ab”}
Output: 4
Explanation:
All possible combinations are {“”, “ab”, “cd”, “abcd”, “cdab”}.
Therefore, maximum length possible is 4.
Input: arr[] = {“abcdefgh”}
Output: 8
Explanation:
All possible combinations are: “”, “abcdefgh”.
Therefore, the maximum length possible is 8.
方法:想法是使用递归。
请按照以下步骤解决问题:
- 从左到右迭代并将每个字符串视为可能的起始子字符串。
- 初始化一个 HashSet 来存储目前遇到的不同字符。
- 一旦一个字符串被选为起始子字符串,检查每个剩余的字符串,如果它只包含以前没有出现过的字符。将此字符串作为子字符串附加到正在生成的当前字符串。
- 执行上述步骤后,打印已生成的字符串的最大长度。
下面是上述方法的实现:
C++
// C++ Program to implement
// the above approach
#include
using namespace std;
// Function to check if all the
// string characters are unique
bool check(string s)
{
set a;
// Check for repetition in
// characters
for (auto i : s) {
if (a.count(i))
return false;
a.insert(i);
}
return true;
}
// Function to generate all possible strings
// from the given array
vector helper(vector& arr,
int ind)
{
// Base case
if (ind == arr.size())
return { "" };
// Consider every string as
// a starting substring and
// store the generated string
vector tmp
= helper(arr, ind + 1);
vector ret(tmp.begin(),
tmp.end());
// Add current string to result of
// other strings and check if
// characters are unique or not
for (auto i : tmp) {
string test = i + arr[ind];
if (check(test))
ret.push_back(test);
}
return ret;
}
// Function to find the maximum
// possible length of a string
int maxLength(vector& arr)
{
vector tmp = helper(arr, 0);
int len = 0;
// Return max length possible
for (auto i : tmp) {
len = len > i.size()
? len
: i.size();
}
// Return the answer
return len;
}
// Driver Code
int main()
{
vector s;
s.push_back("abcdefgh");
cout << maxLength(s);
return 0;
}
Java
// Java program to implement
// the above approach
import java.util.*;
import java.lang.*;
class GFG{
// Function to check if all the
// string characters are unique
static boolean check(String s)
{
HashSet a = new HashSet<>();
// Check for repetition in
// characters
for(int i = 0; i < s.length(); i++)
{
if (a.contains(s.charAt(i)))
{
return false;
}
a.add(s.charAt(i));
}
return true;
}
// Function to generate all possible
// strings from the given array
static ArrayList helper(ArrayList arr,
int ind)
{
ArrayList fin = new ArrayList<>();
fin.add("");
// Base case
if (ind == arr.size() )
return fin;
// Consider every string as
// a starting substring and
// store the generated string
ArrayList tmp = helper(arr, ind + 1);
ArrayList ret = new ArrayList<>(tmp);
// Add current string to result of
// other strings and check if
// characters are unique or not
for(int i = 0; i < tmp.size(); i++)
{
String test = tmp.get(i) +
arr.get(ind);
if (check(test))
ret.add(test);
}
return ret;
}
// Function to find the maximum
// possible length of a string
static int maxLength(ArrayList arr)
{
ArrayList tmp = helper(arr, 0);
int len = 0;
// Return max length possible
for(int i = 0; i < tmp.size(); i++)
{
len = len > tmp.get(i).length() ? len :
tmp.get(i).length();
}
// Return the answer
return len;
}
// Driver code
public static void main (String[] args)
{
ArrayList s = new ArrayList<>();
s.add("abcdefgh");
System.out.println(maxLength(s));
}
}
// This code is contributed by offbeat
Python3
# Python3 program to implement
# the above approach
# Function to check if all the
# string characters are unique
def check(s):
a = set()
# Check for repetition in
# characters
for i in s:
if i in a:
return False
a.add(i)
return True
# Function to generate all possible
# strings from the given array
def helper(arr, ind):
# Base case
if (ind == len(arr)):
return [""]
# Consider every string as
# a starting substring and
# store the generated string
tmp = helper(arr, ind + 1)
ret = tmp
# Add current string to result of
# other strings and check if
# characters are unique or not
for i in tmp:
test = i + arr[ind]
if (check(test)):
ret.append(test)
return ret
# Function to find the maximum
# possible length of a string
def maxLength(arr):
tmp = helper(arr, 0)
l = 0
# Return max length possible
for i in tmp:
l = l if l > len(i) else len(i)
# Return the answer
return l
# Driver Code
if __name__=='__main__':
s = []
s.append("abcdefgh")
print(maxLength(s))
# This code is contributed by pratham76
C#
// C# program to implement
// the above approach
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
class GFG{
// Function to check if all the
// string characters are unique
static bool check(string s)
{
HashSet a = new HashSet();
// Check for repetition in
// characters
for(int i = 0; i < s.Length; i++)
{
if (a.Contains(s[i]))
{
return false;
}
a.Add(s[i]);
}
return true;
}
// Function to generate all possible
// strings from the given array
static ArrayList helper(ArrayList arr,
int ind)
{
// Base case
if (ind == arr.Count)
return new ArrayList(){""};
// Consider every string as
// a starting substring and
// store the generated string
ArrayList tmp = helper(arr, ind + 1);
ArrayList ret = new ArrayList(tmp);
// Add current string to result of
// other strings and check if
// characters are unique or not
for(int i = 0; i < tmp.Count; i++)
{
string test = (string)tmp[i] +
(string)arr[ind];
if (check(test))
ret.Add(test);
}
return ret;
}
// Function to find the maximum
// possible length of a string
static int maxLength(ArrayList arr)
{
ArrayList tmp = helper(arr, 0);
int len = 0;
// Return max length possible
for(int i = 0; i < tmp.Count; i++)
{
len = len > ((string)tmp[i]).Length ? len :
((string)tmp[i]).Length;
}
// Return the answer
return len;
}
// Driver Code
public static void Main(string[] args)
{
ArrayList s = new ArrayList();
s.Add("abcdefgh");
Console.Write(maxLength(s));
}
}
// This code is contributed by rutvik_56
C++
#include
using namespace std;
int maxLength(vector& A)
{
vector > dp
= { bitset<26>() }; // auxillary dp storage
int res = 0; // will store number of unique chars in
// resultant string
for (auto& s : A) {
bitset<26> a; // used to track unique chars
for (char c : s)
a.set(c - 'a');
int n = a.count();
if (n < s.size())
continue; // duplicate chars in current string
for (int i = dp.size() - 1; i >= 0; --i) {
bitset<26> c = dp[i];
if ((c & a).any())
continue; // if 1 or more char common
dp.push_back(c | a); // valid concatenation
res = max(res, (int)c.count() + n);
}
}
return res;
}
int main()
{
vector v = { "ab", "cd", "ab" };
int ans = maxLength(v);
cout << ans; // resultant answer string : cfbdghzest
return 0;
}
输出
8
时间复杂度: O(2 N )
辅助空间: O(N * 2 N )
高效方法(使用动态规划):
C++
#include
using namespace std;
int maxLength(vector& A)
{
vector > dp
= { bitset<26>() }; // auxillary dp storage
int res = 0; // will store number of unique chars in
// resultant string
for (auto& s : A) {
bitset<26> a; // used to track unique chars
for (char c : s)
a.set(c - 'a');
int n = a.count();
if (n < s.size())
continue; // duplicate chars in current string
for (int i = dp.size() - 1; i >= 0; --i) {
bitset<26> c = dp[i];
if ((c & a).any())
continue; // if 1 or more char common
dp.push_back(c | a); // valid concatenation
res = max(res, (int)c.count() + n);
}
}
return res;
}
int main()
{
vector v = { "ab", "cd", "ab" };
int ans = maxLength(v);
cout << ans; // resultant answer string : cfbdghzest
return 0;
}
输出
10
时间复杂度: O(N^2)
辅助空间: O(N * 26)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。