Word Break

来源:互联网 发布:无线信号探测软件 编辑:程序博客网 时间:2024/04/30 10:20

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

只是判断s是否可以拆分。使用递归实现超时。

public boolean wordBreak(String s, Set<String> wordDict) {return helper(s,wordDict,0);}private boolean helper(String s,Set<String> set,int start){if(start==s.length())return true;for(String t:set){int len=t.length();if(start+len>s.length())continue;if(s.substring(start, start+len).equals(t)){if(helper(s,set,start+len))return true;}}return false;}

采用动态规划。

public boolean wordBreak2(String s,Set<String> set){boolean[] t=new boolean[s.length()+1];t[0]=true;for(int i=0;i<s.length();i++){if(!t[i])continue;for(String str:set){int len=str.length();if(i+len>s.length())continue;if(t[i+len])continue;if(s.substring(i, i+len).equals(str))t[i+len]=true;}}return t[s.length()];}



0 0
原创粉丝点击