Word Break

来源:互联网 发布:淘客软件 编辑:程序博客网 时间:2024/06/03 14:20
public class Solution {    public boolean wordBreak(String s, Set<String> wordDict) {        if (s == null || s.length() ==0) {            return true;        }        int maxLength = maxLength(wordDict);        boolean[] canBeSegemented = new boolean[s.length() + 1];        canBeSegemented[0] = true;        for (int i = 1; i <= s.length(); i++) {            canBeSegemented[i] = false;            for (int j = 1; j <= maxLength && j <= i; j++) {                if (!canBeSegemented[i - j]) {                    continue;                }                String newWord = s.substring(i - j, i);                if (wordDict.contains(newWord)) {                    canBeSegemented[i] = true;                    break;                }            }        }        return canBeSegemented[s.length()];    }    private int maxLength (Set<String> wordDict) {        int maxLength = 0;        for (String word : wordDict) {            maxLength = Math.max(word.length(), maxLength);        }        return maxLength;    }}

0 0
原创粉丝点击