fork download
  1. package com.ferhatelmas;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.HashMap;
  6. import java.util.List;
  7.  
  8. class Tokenizer {
  9.  
  10. private HashMap<String, String> dict;
  11.  
  12. public Tokenizer(String[] words) {
  13. this.dict = new HashMap<String, String>();
  14.  
  15. for(String word : words)
  16. dict.put(sorted(word), word);
  17. }
  18.  
  19. public static String sorted(String w) {
  20. char[] chars = w.toCharArray();
  21. Arrays.sort(chars);
  22. return new String(chars);
  23. }
  24.  
  25. public List<String> getWords(String sentence) {
  26.  
  27. if(sentence.isEmpty()) return new ArrayList<String>();
  28.  
  29. List<String> words = new ArrayList<String>();
  30. int len = sentence.length();
  31. for(int i=1; i<=len; i++) {
  32. String token = sorted(sentence.substring(0, i));
  33. if(dict.containsKey(token)) {
  34. List<String> found = getWords(sentence.substring(i));
  35.  
  36. if(found != null) {
  37. words.add(dict.get(token));
  38. words.addAll(found);
  39. break;
  40. }
  41. }
  42. }
  43.  
  44. return words.size() == 0 ? null : words;
  45. }
  46.  
  47. public static void main(String[] args) {
  48. Tokenizer t = new Tokenizer(new String[] {"ferhat", "elmas", "huseyn", "gasimov", "that", "is", "a", "sample"});
  49. List<String> words = t.getWords("usnyehttahsiaaspmle");
  50. if(words != null) // unmatched returns null since empty string returns empty list
  51. for(String w : words)
  52. System.out.println(w);
  53. }
  54. }
Runtime error #stdin #stdout #stderr 0.05s 974336KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: Could not find or load main class Tokenizer