Return true because "leetcode" can be segmented as "leet code".
判断输入的字符串能否被拆分成字典中的两个单词。
例如:输入字符串"cars" 字典:"car", “ca”, "rs", 返回:true。
解题报告:
解法1:DFS,直接深搜,而且本题不要求字典中的单词唯一,所以DFS过程中不需要改变字典。但大数据TLE。
public class Solution { public boolean wordBreak(String s, Set<String> dict) { if(dict.size()==0) { return false; } Iterator<String> it = dict.iterator(); while (it.hasNext()) { String str = it.next(); if(s.equals(str)) { return true; } if(s.indexOf(str)==0) { if(wordBreak(s.substring(str.length()),dict)==true) { return true; } } } return false; } }
public boolean wordBreak(String s, Set<String> dict) { if(dict.isEmpty()) { return false; } if(s.length()==0) { return true; } int[] state = new int[s.length() + 1]; state[0] = 1; for(int i=1;i<=s.length();i++) { for(int j=0;j<i;j++) { if(state[j]==1&&(dict.contains(s.substring(j,i))==true)) { state[i] = 1; break; } } } if(state[s.length()]==1) { return true; } else { return false; } }