Dynamic Programming - Word Break

后端 未结 2 1238
余生分开走
余生分开走 2021-01-07 09:35

I am trying to solve this Problem.The question is as follows
Given an input string and a dictionary of words, find out if the input string can be segmented into a space-

2条回答
  •  天命终不由人
    2021-01-07 09:53

    Is recursion mandatory? I see, iterative DP-solution is easiest and compact:

    #include 
    #include 
    
    int main() {
      const char *D[] = { "i", "like", "sam", "sung", "samsung", "mobile", "ice", "cream", "icecream", "man", "go", "mango", NULL};
      const char q[] = "samsungmango";
      char dp[100];
      short d_len[20];
      memset(dp, 0, sizeof(dp));
      dp[0] = 1; // 0 element is always reacheable
      int i, j;
      // compute dict string lengths
      for(i = 0; D[i]; i++)
          d_len[i] = strlen(D[i]);
    
      // Compute splits using DP array
      for(i = 0; q[i] != 0; i++)
          if(dp[i])  // this index is reacheable
              for(j = 0; D[j]; j++) // try to make next reacheable indexes
                  if(strncmp(&q[i], D[j], d_len[j]) == 0)
                      dp[i + d_len[j]] = 1; // That position is reacheable, too
    
      // if EOLN(q) is reached, then yes
      printf("Answer is %s\n", dp[i]? "YES" : "NO");
    
    } // main
    

提交回复
热议问题