- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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:
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))
["xyz", "xyw", "wab", "cde"]
- 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?
- Program to find length of substring with consecutive common characters in Python
- Program to find length of longest consecutive sublist with unique elements in Python
- Program to find total number of strings, that contains one unique characters in Python
- Program to count number of unique palindromes we can make using string characters in Python
- Program to find min length of run-length encoding after removing at most k characters in Python
- Program to find length of longest substring which contains k distinct characters in Python
- Python program to check if a string contains all unique characters
- Program to find minimum required chances to form a string with K unique characters in Python
- Program to find sum of unique elements in Python
- C++ Program to Find the Length of a String
- C program to find the length of a string?