Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
Algorithm
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))
True
How It Works
The algorithm uses recursive backtracking to check if the string can be segmented:
- Base case: If we've processed the entire string (i == len(s)), return True
- Word building: Build words character by character from current position
- Validation: If the current word exists in our word set, recursively check the remaining string
- Backtrack: If no valid segmentation found, return False
Alternative Approach Using Dynamic Programming
For better performance with large strings, we can use dynamic programming ?
def can_break_string(words, s):
word_set = set(words)
dp = [False] * (len(s) + 1)
dp[0] = True
for i in range(1, len(s) + 1):
for j in range(i):
if dp[j] and s[j:i] in word_set:
dp[i] = True
break
return dp[len(s)]
words = ["love", "python", "we", "programming", "language"]
s = "welovepythonprogramming"
print(can_break_string(words, s))
True
Comparison
| Approach | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Recursive | O(2^n) | O(n) | Simple implementation |
| Dynamic Programming | O(n²) | O(n) | Large strings, better performance |
Conclusion
The recursive approach provides a clear solution for checking string segmentation. For better performance with larger inputs, the dynamic programming approach is more efficient with O(n²) time complexity.
