每天一道算法題(五)Leetcode – Word Break (Java)

問題

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

For example, given
s = “leetcode”,
dict = [“leet”, “code”].

Return true because “leetcode” can be segmented as “leet code”.
即:是否可以把一個字符串拆分成單詞字典dict的一個或多個詞


動態規劃解法

因爲這兩天接觸了動態規劃,所以我準備試試能不能用dp算法去解出這道題。
思路:

    • 建一個數組來存儲狀態dp,空串或前面是dict裏單詞的字符的index所在的狀態是true
  1. 定義一個初始狀態,dp[0] = true,即空串爲true
  2. 根據dict裏面的單詞字符創去和以從字符串第一個字符開始的字符串比較,如果相等,給字符串中的這個單詞的下一個字符的dp[nextChar] = true;
  3. 根據狀態進行一些判斷

代碼:

    public boolean wordBreak(String str ,Set<String> dict {

        boolean[] dp = new boolean[str.length()+1];
        dp[0] = true;//set first to be true, why?
        //Because we need initial state

        for (int i = 0; i < str.length(); i++) {
            //should continue from match position
            if (!dp[i]) 
                continue; 

            for (String word : dict) {
                int len = word.length();
                int end = i + len;

                if (end > str.length()) 
                    continue;

                if (dp[end]) 
                    continue;

                if (str.substring(i , end).equals(word)) {
                    dp[end] = true;
                }
            }
        }
        return dp[str.length()];
    }
    @Test
    public void testWordBreak(){
        String str = "leetcode";
        String[] strs = {"leet", "code"};  
        Set<String> dict = new HashSet<String>(Arrays.asList(strs));  
        System.out.println(wordBreak(str, dict));
    }

遞歸法 (轉載)

我又研究一下其他人的方法,記錄一下遞歸法

  • 理解思路:
  • 1.這是一個遞歸
  • 2.遞歸的方法是解題的核心
  • 3.遞歸需要有一個結束條件,本題的結束條件就是start == s.length()

        public boolean wordBreak(String s, Set<String> dict) {
                 return wordBreakHelper(s, dict, 0);
        }

        public boolean wordBreakHelper(String s, Set<String> dict, int start){
            if(start == s.length()) 
                return true;

            for(String a: dict){
                int len = a.length();
                int end = start+len;

                //end index should be <= string length
                if(end > s.length()) 
                    continue;

                if(s.substring(start, start+len).equals(a))
                    if(wordBreakHelper(s, dict, start+len))
                        return true;
                }
            return false;
        }

正則表達式法 (轉載)

    public static void main(String[] args) {
        HashSet<String> dict = new HashSet<String>();
        dict.add("go");
        dict.add("goal");
        dict.add("goals");
        dict.add("special");

        StringBuilder sb = new StringBuilder();

        for(String s: dict){
            sb.append(s + "|");
        }

        String pattern = sb.toString().substring(0, sb.length()-1);
        pattern = "("+pattern+")*";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher("goalspecial");

        if(m.matches()){
            System.out.println("match");
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章