Word Break--lintcode

Description

Given a string s and a dictionary of words dict, determine if s can be break into a space-separated sequence of one or more dictionary words.

給出一個字符串s和一個詞典,判斷字符串s是否可以被空格切分成一個或多個出現在字典中的單詞

Example

Given s = “lintcode”, dict = [“lint”, “code”].

Return true because “lintcode” can be break as “lint code”.

我的思路:動態規劃題。主要找分割點。利用兩個for循環。外層循環來控制待驗證的字符串的長度,而用內層的循環來尋找這麼一個分割點,可以把字符串分成一個單詞和一個同樣可分解的子字符串。同時,我們用數組記錄下字符串長度遞增時可分解的情況,以供之後使用,避免重複計算。

這裏寫圖片描述
如圖:從d到l 一個一個找。到c了 co,cd字典裏沒有,code字典裏有,而且dp[j+1]==true,下標爲i,則dp[i]=ture.
code是字典裏有的,i代表c在s和dp數組中的下標,j代表e在S和dp數組中的下標。如果要符合題目要求的話,字典裏的一些字符串拼接起來等於S,所以dp[j+1]==true。這個條件 就是讓判斷是否可以拼接。如找到a的時候 找到的字符串是lint.此時的j+1正好是c的下標。對應的dp[j+1]==true。說明可以拼接。 所以可以將dp[i]=true.

 public boolean wordBreak(String s, Set<String> wordDict) {
        boolean[] dp = new boolean[s.length()+1];
        Arrays.fill(dp,false);
        dp[s.length()]=true;
        // 外層循環遞增長度
        for(int i = s.length()-1; i >=0 ; i--){
            // 內層循環尋找分割點
            for(int j = i; j < s.length(); j++){
                String sub = s.substring(i,j+1);
                if(wordDict.contains(sub) && dp[j+1]){
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[0];
    }

這個參考網址:https://segmentfault.com/a/1190000003698693

但是運行的時候 超時。。。我以爲這個還不夠簡潔或者思路不對,換了好幾個網上搜的,都是超時。。。我都要放棄這個題了,心灰意冷了。 好歹堅持了一下,又到處翻,翻到了 官網提供的標準答案:
地址:http://www.jiuzhang.com/solution/word-break

public boolean wordBreak(String s, Set<String> dict) {
        // write your code here
        if (s == null || s.length() == 0) {
            return true;
        }

        int maxLength = getMaxLength(dict);
        boolean[] canSegment = new boolean[s.length() + 1];

        canSegment[0] = true;
        for (int i = 1; i <= s.length(); i++) {
            canSegment[i] = false;
            for (int lastWordLength = 1;
                     lastWordLength <= maxLength && lastWordLength <= i;
                     lastWordLength++) {
                if (!canSegment[i - lastWordLength]) {
                    continue;
                }
                String word = s.substring(i - lastWordLength, i);
                if (dict.contains(word)) {
                    canSegment[i] = true;
                    break;
                }
            }
        }

        return canSegment[s.length()];
    }
    private int getMaxLength(Set<String> dict) {
        int maxLength = 0;
        for (String word : dict) {
            maxLength = Math.max(maxLength, word.length());
        }
        return maxLength;
    }

這個代碼思路是根據長度來的。從前到後 的長度,思想是差不多的,就是寫法問題。爲什麼 它加了一個maxLength就不會超時,這個我不理解。。。

發佈了53 篇原創文章 · 獲贊 5 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章