word break II 對字符串根據已知字典 分解出所有可能組合

採用暴力法(brute force 簡稱BF,普通模式匹配)

思路:1,首先判斷字符串的第一個字符在不在字典裏,如果在,判斷第二個字符在不在字典裏,如果不在,前兩個字符在不在字典裏,依次迭代;

          2,這裏用到了遞歸,如果滿足條件則往後遍歷下去,存中間結果,直到遍歷到了字符串的末尾 ,這時候就出現一個可以分解的組合,存入rsList

    代碼如下:       

public class Solution {
public List<string> wordBreak(String s, Set<string> dict) {
List<string> rsList = new ArrayList<string>();
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<string> dict, List<string> 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;
              newTempStr=tempStr.length()<1?temp:(tempStr+" "+temp)
wordBreakHelper(s, i, newTempStr, dict, rsList);
}
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章