您的位置:首页 > 其它

LintCode:单词切分

2017-06-20 20:45 369 查看
一.题目描述

给出一个字符串s和一个词典,判断字符串s是否可以被空格切分成一个或多个出现在字典中的单词。

从输入和输出的结果看加上个人的理解,想加多两点说明:

1)原字符串可以被多个空格切分开

2)被切分开的子字符串都必须要在词典中有对应的字段

二.解题思路

其实从"是否可以"上理解,只要找到符合条件的情况即可而无需遍历,布尔数组为真是能分割的点,后面的子串根据上一个数组为真的位置开始判断是否能被分割。

public class Solution {
/**
* @param s: A string s
* @param dict: A dictionary of words dict
*/
public boolean wordBreak(String s, Set<String> dict) {
if (s == null || s.length() == 0) {
return true;
}

int maxLength = 0;

Iterator<String> iter = dict.iterator();
while (iter.hasNext()) {
String str = iter.next();
maxLength = Math.max(maxLength, str.length());
}

boolean[] canBreak = new boolean[s.length() + 1];

canBreak[0] = true;
for (int i = 1; i <= s.length(); i++) {
canBreak[i] = false;
for (int wordLength = 1;
wordLength <= maxLength && wordLength <= i;
wordLength++) {
String word = s.substring(i - wordLength, i);

if (canBreak[i - wordLength] && dict.contains(word)) {
canBreak[i] = true;
break;
}
}
}

return canBreak[s.length()];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: