程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> [LeetCode] Word Break II

[LeetCode] Word Break II

編輯:C++入門知識

[LeetCode] Word Break II


題目鏈接:https://oj.leetcode.com/problems/word-break-ii/

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].
A solution is ["cats and dog", "cat sand dog"].

思路:還是DFS遞歸遍歷。采用動態規劃比較麻煩,需要存儲當前位置能夠實現 word break的所有結果的和,空間復雜度很高,不劃算,代碼寫起來還很麻煩。

public class Solution {
    public List wordBreak(String s, Set dict) {
        List rsList = new ArrayList();
        if (s == null || s.length() < 1 || dict == null) {
            return rsList;
        }
        
        wordBreakHelper(s, 0, "", dict, rsList);
        
        return rsList;
    }
    
    public void wordBreakHelper(String s, int start, String tempStr, Set dict, List rsList)  {
        if (start >= s.length()) {
            rsList.add(tempStr);
            return;
        }
        
        for (int i = start + 1; i <= s.length(); i++) {
            String temp = s.substring(start, i);
            if (dict.contains(temp)) {
                String newTempStr;
                if (tempStr.length() < 1) {
                    newTempStr = temp;
                } else {
                    newTempStr = tempStr + " " + temp;
                }
                
                wordBreakHelper(s, i, newTempStr, dict, rsList);
            }
        }
    }
}

用這個方法還是有一個結果TLE,將WordBreak的方法放到前面先判斷一下是否能夠word break 後再進行下面的程序就可以AC

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved