热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

通过连接字符串数组中的字符来最大化字符串的长度

通过连接字符串数组中的字符来最大化字符串的长度原文:https:

通过连接字符串数组中的字符来最大化字符串的长度

原文:https://www.geeksforgeeks.org/maximize-length-of-the-string-by-concatenating-characters-from-an-array-of-strings/

给定字符串数组arr[],任务是找到可以通过连接给定数组的子序列而生成的不同字符字符串的最大可能长度。

示例

输入arr [] = {"ab", "cd", "ab"}

输出:4

说明:所有可能的组合为{"", "ab", "cd", "abcd", "cdab"}

因此,最大长度可能是 4。

输入arr [] = {"abcdefgh"}

输出:8

说明

所有可能的组合是:"" , "abcdefgh"

因此,最大长度为 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 repetation in
    // characters
    for (auto i : s) {
        if (a.count(i))
            return false;
        a.insert(i);
    }
    return true;
}
// Funcyion 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 <    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 repetation in
    // characters
    for(int i = 0; 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     {
        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     {
        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

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 repetation in
    // characters
    for(int i = 0; i     {
        if (a.Contains(s[i]))
        {
            return false;
        }
        a.Add(s[i]);
    }
    return true;
}
// Funcyion 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     {
        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     {
        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

输出: 

8

时间复杂度O(2 ^ N)

辅助空间O(N * 2 ^ N)





推荐阅读
  • 本文详细介绍了 Dockerfile 的编写方法及其在网络配置中的应用,涵盖基础指令、镜像构建与发布流程,并深入探讨了 Docker 的默认网络、容器互联及自定义网络的实现。 ... [详细]
  • Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ... [详细]
  • Java 中 Writer flush()方法,示例 ... [详细]
  • 本文介绍了如何使用 Spring Boot DevTools 实现应用程序在开发过程中自动重启。这一特性显著提高了开发效率,特别是在集成开发环境(IDE)中工作时,能够提供快速的反馈循环。默认情况下,DevTools 会监控类路径上的文件变化,并根据需要触发应用重启。 ... [详细]
  • Java 中的 BigDecimal pow()方法,示例 ... [详细]
  • 本文详细介绍了如何在Linux系统上安装和配置Smokeping,以实现对网络链路质量的实时监控。通过详细的步骤和必要的依赖包安装,确保用户能够顺利完成部署并优化其网络性能监控。 ... [详细]
  • 本文详细介绍了Java中org.eclipse.ui.forms.widgets.ExpandableComposite类的addExpansionListener()方法,并提供了多个实际代码示例,帮助开发者更好地理解和使用该方法。这些示例来源于多个知名开源项目,具有很高的参考价值。 ... [详细]
  • 深入解析Spring Cloud Ribbon负载均衡机制
    本文详细介绍了Spring Cloud中的Ribbon组件如何实现服务调用的负载均衡。通过分析其工作原理、源码结构及配置方式,帮助读者理解Ribbon在分布式系统中的重要作用。 ... [详细]
  • 本文介绍如何使用 Python 将一个字符串按照指定的行和元素分隔符进行两次拆分,最终将字符串转换为矩阵形式。通过两种不同的方法实现这一功能:一种是使用循环与 split() 方法,另一种是利用列表推导式。 ... [详细]
  • 本文详细介绍了Java中org.neo4j.helpers.collection.Iterators.single()方法的功能、使用场景及代码示例,帮助开发者更好地理解和应用该方法。 ... [详细]
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • Windows服务与数据库交互问题解析
    本文探讨了在Windows 10(64位)环境下开发的Windows服务,旨在定期向本地MS SQL Server (v.11)插入记录。尽管服务已成功安装并运行,但记录并未正确插入。我们将详细分析可能的原因及解决方案。 ... [详细]
  • 1.如何在运行状态查看源代码?查看函数的源代码,我们通常会使用IDE来完成。比如在PyCharm中,你可以Ctrl+鼠标点击进入函数的源代码。那如果没有IDE呢?当我们想使用一个函 ... [详细]
  • 主要用了2个类来实现的,话不多说,直接看运行结果,然后在奉上源代码1.Index.javaimportjava.awt.Color;im ... [详细]
  • 使用 Azure Service Principal 和 Microsoft Graph API 获取 AAD 用户列表
    本文介绍了一段通用代码示例,该代码不仅能够操作 Azure Active Directory (AAD),还可以通过 Azure Service Principal 的授权访问和管理 Azure 订阅资源。Azure 的架构可以分为两个层级:AAD 和 Subscription。 ... [详细]
author-avatar
鸵鸟家的大pp
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有