CareerCup String getSentence(String text, Set<String> dictionary); O(n)

来源:互联网 发布:怪物猎人ol捏脸数据图 编辑:程序博客网 时间:2024/05/22 00:13
String getSentence(String text, Set<String> dictionary); 

// text is a string without spaces, you need to insert spaces into text, so each word seperated by the space in the resulting string exists in the dictionary, return the resulting string 

// running time has to be at least as good as O(n) 

// getSentence("iamastudentfromwaterloo", {"from, "waterloo", "hi", "am", "yes", "i", "a", "student"}) -> "i am a student from waterloo"

---------------------------------------------------------------

import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set;class Solution {public static void main(String[] args) {Solution instance = new Solution();Set<String> dictionary = new HashSet();dictionary.add("google");dictionary.add("is");dictionary.add("awesome");List<String> store = new ArrayList<String>();instance.printWords("googleisawesome", store, dictionary);for(int i = store.size() - 1; i >= 0; --i) {System.out.println(store.get(i));}}private boolean printWords(String string, List<String> store, Set<String> dictionary) {if(string.length() == 0) {return true;}for(int i = 1; i <= string.length(); ++i) {String curWord = string.substring(0, i);if(dictionary.contains(curWord) && printWords(string.substring(i), store, dictionary)) {store.add(curWord);return true;}}return false;}}


0 0