fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. Set<String> wordDict = new HashSet<String>();
  13. wordDict.add("lee");
  14. wordDict.add("tco");
  15. wordDict.add("de");
  16. wordDict.add("leet");
  17. wordDict.add("code");
  18.  
  19. wordBreak("leetcode", wordDict);
  20. }
  21.  
  22. public static boolean wordBreak(String s, Set<String> wordDict) {
  23. if(s == null || wordDict.size() == 0)
  24. return false;
  25.  
  26. int n = s.length();
  27. int[] dp = new int[n + 1];
  28. Arrays.fill(dp, -1);
  29.  
  30. dp[0] = 0;
  31.  
  32. for (int i=0; i<n; i++) {
  33. if(dp[i] != -1) {
  34. for (int j=i+1; j<=n; j++) {
  35. if (wordDict.contains(s.substring(i, j))) {
  36. dp[j] = i;
  37. }
  38. }
  39. }
  40. }
  41.  
  42. for(int i=0; i<dp.length; i++) {
  43. System.out.println(dp[i]);
  44. }
  45.  
  46. return dp[s.length()] != -1;
  47. }
  48. }
Success #stdin #stdout 0.07s 3359744KB
stdin
Standard input is empty
stdout
0
-1
-1
0
0
-1
3
-1
6