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

[LeetCode]Word Break

編輯:C++入門知識

[LeetCode]Word Break


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".


利用遞歸動態規劃,而且遞歸的條件要有限制

public class Solution {
	boolean f[];
    public boolean wordBreak(String s, Set dict) {
    	f = new boolean[s.length()];
    	wordBreak(s,dict,0);
    	return f[s.length()-1];
    }
    
    private void wordBreak(String s, Set dict,int index){
    	if(index>=s.length()) return;
    	for(int i=index;i

參考九章算法,提取出set裡字符串的最長距離,可以進一步減小算法

public class Solution {
	boolean f[];
	int maxLen = Integer.MIN_VALUE;

    public boolean wordBreak(String s, Set dict) {
    	f = new boolean[s.length()];
    	maxLength(dict);
    	wordBreak(s,dict,0);
    	return f[s.length()-1];
    }
    
    private void wordBreak(String s, Set dict,int index){
    	if(index>=s.length()) return;
    	for(int i=index;i dict){
    	Iterator it = dict.iterator();
    	while(it.hasNext()){
    		maxLen = Math.max(maxLen, it.next().length());
    	}
    }
}





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