Is there any way to convert my TLE code to a valid solution?


  • 0
    C

    Is there any way to convert my TLE code to a valid solution?

        public List<String> wordBreak(String s, List<String> wordDict) {
            Set<String> dict = new HashSet<String>();
            for (String word : wordDict){
                dict.add(word);
            }
            List<String> res = new ArrayList<String>();
            helper(s, dict, "", res);
            return res;
        }       
    
        private void helper(String s, Set<String> dict, String currString, List<String> res) {
            if (s.length() == 0) {
                res.add(currString);
            }  else{
                for (String word : dict) {
                    if (s.startsWith(word)) {
                        String old = currString;
                        currString = currString + (currString.equals("") ? "" : " ") + word;
                        helper(s.substring(word.length()), dict, currString, res);
                        currString = old;
                    }
                }     
            }
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.