
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find length of concatenated string of unique characters in Python?
Suppose we have a list of strings words. We have to make a string that is constructed by concatenating a subsequence of words such that each letter is unique. We have to finally find the length of the longest such concatenation.
So, if the input is like words = ["xyz", "xyw", "wab", "cde"], then the output will be 9, as we cannot pick any word since they contain duplicate characters.
To solve this, we will follow these steps
ans := 0
Define a function recur() . This will take i:= 0, cur:= blank string
if i is same as size of words , then ans := maximum of ans and size of cur return recur(i + 1, cur) if all characters in words[i] are unique and all characters in (cur + words[i]) are unique, then recur(i + 1, cur + words[i]) From the main method do the following: recur() return ans
Let us see the following implementation to get better understanding:
Example
class Solution: def solve(self, words): ans = 0 def is_all_unique(s): return len(set(s)) == len(s) def recur(i=0, cur=""): nonlocal ans if i == len(words): ans = max(ans, len(cur)) return recur(i + 1, cur) if is_all_unique(words[i]) and is_all_unique(cur + words[i]): recur(i + 1, cur + words[i]) recur() return ans ob = Solution() words = ["xyz", "xyw", "wab", "cde"] print(ob.solve(words))
Input
["xyz", "xyw", "wab", "cde"]
Output
9
- Related Articles
- Maximum Length of a Concatenated String with Unique Characters in C++
- Concatenated string with uncommon characters in Python program
- Concatenated string with uncommon characters in Python?
- How to find unique characters of a string in JavaScript?
- Program to count number of unique palindromes we can make using string characters in Python
- Program to find minimum required chances to form a string with K unique characters in Python
- Python program to check if a string contains all unique characters
- Program to find length of substring with consecutive common characters in Python
- Program to find total number of strings, that contains one unique characters in Python
- Program to find length of longest consecutive sublist with unique elements in Python
- Python Program to find mirror characters in a string
- Program to find length of longest substring which contains k distinct characters in Python
- How to print concatenated string in Python?
- Program to find min length of run-length encoding after removing at most k characters in Python
- Python program to find the sum of Characters ascii values in String List

Advertisements