GeeksforGeeks » Interview Questions
Google Interview Question for Software Engineer/Developer about Algorithms, Strings
(8 posts)-
Given a string containing multiple words such that spaces between words is missing. Also, you have a dictionary containing valid words.
Ex. "Thatwouldbefantastic"
Output a string with proper spaces inserted.
Output - "That would be fantastic"
The case of words like bandwidth present can be discounted.
-
How will u split awesome....
single word awesome....????2 words awe some???
or 3 words a we some?????
-
You may assume that the dictionary is contains only those words which do not produce any conflicts. For example, for awesome, you may assume that awe is not there is dictionary.
-
Build a trie-tree of words present in dictionary.
Start traversing the string from beginning and simultaneously traverse down the trie-tree from root. Whenever you reach the end of a word in tree, give a space in output string and again traverse the tree from root for current position in input string.
Repeat till you reach the end of input string. -
To add to vaibhav's solution:
If we later find that we inserted a space in the wrong position such that the given string cannot be divided into words with space, then we can backtrack.
In that case we need to reconsider our decision where we decided to insert our last space char and instead try match a longer word than what has already been identified. If that does not lead us to a solution , we turn to the previous space character and backtrack in that fashion -
@vaibhav, This is a dynamic programming problem. You don't necessarily need to use tries, Thank you.
-
call: checkword("","Thatwouldbefantastic") checkword(String sofar,String tobeprocesed){ if(tobeprocesed.isempty()){ print sofar } else{ for(int i=0;i<tobeprocesed.length;i++) word+=tobeprocesed.get(i) if(word.existsindict()){ sofar=sofar+word+" "; checkword(sofar,tobeprocesed.substring(i)) } } } return; }This seems will work..not tested however...
-
@sundi133, What is the worst case running time of your solution assuming calls to the WORDISINDICT are O(1)? Would it improve with dynamic programming,O(N^^2)? Thank you , Camster.
Reply
You must log in to post.