Skip to content

Instantly share code, notes, and snippets.

@nsivabalan
Created December 1, 2013 03:23
Show Gist options
  • Select an option

  • Save nsivabalan/7728145 to your computer and use it in GitHub Desktop.

Select an option

Save nsivabalan/7728145 to your computer and use it in GitHub Desktop.
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class RetrieveShuffledSentence {
static ArrayList<String> origDictWords ;
static Map<String, String> dictMap;
public static void populateDictionary(String[] dict)
{
origDictWords = new ArrayList<String>();
dictMap = new HashMap<String, String>();
for(String str: dict){
origDictWords.add(str);
char[] temp = str.toCharArray();
Arrays.sort(temp);
dictMap.put(new String(temp), str);
}
}
private static boolean ifWord(String str)
{
char[] temp = str.toCharArray();
Arrays.sort(temp);
return dictMap.containsKey(new String(temp));
}
private static String getWord(String str)
{
char[] temp = str.toCharArray();
Arrays.sort(temp);
return dictMap.get(new String(temp));
}
private static boolean getShuffledWords(String str, int index, ArrayList<Integer> result )
{
if(index == str.length())
{
return true;
}
int curIndex = index;
while(curIndex <= str.length())
{
if(ifWord(str.substring(index, curIndex)))
{
result.add(curIndex);
if(getShuffledWords(str, curIndex, result))
return true;
else
result.remove(result.size()-1);
}
curIndex++;
}
return false;
}
public static void getWords(String str, String[] dict)
{
if(str == null || dict == null || dict.length == 0) return;
populateDictionary(dict);
ArrayList<Integer> result = new ArrayList<Integer>();
StringBuffer res = new StringBuffer();
if(getShuffledWords(str, 0, result))
{
int prev = 0;
int counter = 0;
while(counter < result.size()){
res.append(getWord(str.substring(prev, result.get(counter)))+" ");
prev = result.get(counter);
counter++;
}
}
else{
System.out.println("No solution");
}
System.out.println(res);
}
public static void main(String[] args) {
String[] dict = {"the", "quick", "brown" , "fox", "kqu"};
getWords("hetkuqcirnwboxfo", dict);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment