看的别人的代码改了下
1 class Solution { 2 public: 3 bool wordBreak(string s, unordered_set<string> &dict) { 4 vector<bool> f(s.size()+1); 5 f[0] = true; 6 for (int i = 1; i <= s.size(); i++) { 7 for (int j = 0; j < i; j++) { 8 f[i] = f[j] && (dict.count(s.substr(j, i-j))); 9 if (f[i]) break; 10 } 11 } 12 return f[s.size()]; 13 } 14 };
C#
1 public class Solution { 2 public bool WordBreak(string s, ISet<string> wordDict) { 3 bool[] f = new bool[s.Length+1]; 4 f[0] = true; 5 for (int i = 1; i <= s.Length; i++) { 6 for (int j = 0; j < i; j++) { 7 f[i] = f[j] && (wordDict.Contains(s.Substring(j, i-j))); 8 if (f[i]) break; 9 } 10 } 11 return f[s.Length]; 12 } 13 }