
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If String Can Be Broken Into Given List of Words in Python
Suppose we have a word list and another string s with no spaces. We have to check whether the string can be broken down using the list of words or not.
So, if the input is like words = ["love", "python", "we", "programming", "language"] s = "welovepythonprogramming", then the output will be True
To solve this, we will follow these steps −
- words := a new set of all unique words
- Define a function rec() . This will take i
- if i is same as size of s , then
- return True
- acc := blank string
- for j in range i to size of s, do
- acc := acc concatenate s[j]
- if acc is in words, then
- if rec(j + 1) is True, then
- return True
- if rec(j + 1) is True, then
- return False
- From the main method call rec(0) and return result
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, words, s): words = set(words) def rec(i=0): if i == len(s): return True acc = "" for j in range(i, len(s)): acc += s[j] if acc in words: if rec(j + 1): return True return False return rec() ob = Solution() words = ["love", "python", "we", "programming", "language"] s = "welovepythonprogramming" print(ob.solve(words, s))
Input
["love", "python", "we", "programming", "language"], "welovepythonprogramming"
Output
True
Advertisements