1. 程式人生 > >Leetcode-139. Word Break

Leetcode-139. Word Break

題目:

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

For example, given
s = "leetcode",
dict = ["leet", "code"]

.

Return true because "leetcode" can be segmented as "leet code".

UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

Subscribe to see which companies asked this questio

AC程式碼1:
class Solution {
public:
	bool wordBreak(string s, vector<string>& wordDict) {
		int size = wordDict.size();
		set<string>ma;
		for (vector<string> ::iterator iter = wordDict.begin(); iter != wordDict.end(); iter++)ma.insert((*iter));
		int len = s.size();
		vector<bool>re(len, false);
		string temp;
		for (int i = 0; i < len; i++){
			for (int j = i; j >= 0; j--){
				if (re[j] == true){ 
					temp = s.substr(j + 1, i - j);
					if (ma.find(temp) != ma.end()){
						re[i] = true;
						break;
					}
				}
				if (j == 0){
					temp = s.substr(0, i + 1);
					if (ma.find(temp) != ma.end()){
						re[i] = true;
						break;
					}
				}
			}
		}
		return re[len - 1];
	}
};

AC程式碼2:
 class Solution {
 public:
	 bool wordBreak(string s, vector<string>& wordDict) {
		 int size = wordDict.size();
		 set<string>ma;
		 for (vector<string> ::iterator iter= wordDict.begin();iter!=wordDict.end(); iter++)ma.insert((*iter));
		 int len = s.size();
		 vector<bool>re(len+1,false);
		 re[0] = true;
		 string temp;
		 for (int i = 1; i <=len;i++){
			 for (int j = i-1; j >= 0;j--){
				 if (re[j] == true){
					 temp = s.substr(j, i - j);
					 if (ma.find(temp) != ma.end()){
						 re[i] = true;
						 break;
					 }
				 }
			 }
		 }
		 return re[len];
	 }
 };

解析:

AC程式碼1是自己寫的第一個版本,這時需要注意的的一種情況就是當前下標為i的字母要包含下標為0的字母所組成的字串存在於wordDict中;

AC程式碼2利用一個額外的儲存空間並將re[0]設定為true,這樣的好處就是將AC程式碼1中的特殊情況統一處理,也就是當j遞減到0時,那麼這時字串s就會將第

一個字母包含就去,這種統一化處理方式比較妙!