 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Program to check a string can be broken into given list of words or not 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
 