LeetCode-- word split

topic:

  Given a string s non-empty and non-empty dictionary wordDict comprising a word list, it is determined whether the space s can be split into one or more occurrences of a word in the dictionary;

  Note:

    1, can be reused while splitting word dictionary;

    2, it can be assumed repeated words not in the dictionary;

  

  My idea is to use backtracking, one by one to find s can match the word in the dictionary wordDict

 1 import java.util.*;
 2 
 3 public class Solution {
 4     private List<String> wordDict;
 5     
 6     public boolean wordBreak(String s, List<String> wordDict) {
 7         this.wordDict = wordDict;
 8         return find(s, 0);
 9     }
10     
11     public boolean find(String s, int i)
12     {
13         if(i == s.length())
14         {
15              return  to true ;
 16          }
 . 17          
18 is          for ( int j = I; j <s.length (); j ++)   // Step 2, if the subsequent matching step 1 fails, then the fallback and move the pointer j, to find dictionary contains additional substrings 
. 19          {
 20 is              iF (wordDict.contains (s.substring (I, J + 1 )))  
 21 is              {
 22 is                  iF (Find (S, J + 1))      // step 1, to find the when the word dictionary, matching is continued subsequent 
23 is                  {
 24                      return  to true ;
 25                  }
 26 is              }
 27          }
 28          return false;
29     }
30 }

  Time complexity of the above algorithm, in the best case time complexity of O (n), i.e., only one string traversed, but in the worst case time complexity of O (n ^ 2), i.e., each forward a word, we need to re-iterate a string. In the 36's leetcode test by 29 test, suggesting that the test on some timeout, such as: s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", wordDict = [ "a", "aa", "aaa", "aaaa ] in this test case, the above algorithm will exist "," aaaaa "," aaaaaa "," aaaaaaa "," aaaaaaaa "," aaaaaaaaa "," aaaaaaaaaa "relatively large number of duplicate costs, is there any way to avoid repetition compare it?

 

Guess you like

Origin www.cnblogs.com/latup/p/11730181.html