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()];
}
}
给出一个字符串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()];
}
}
相关文章推荐
- LintCode- 单词切分
- lintcode_单词切分
- lintcode,单词切分
- **[Lintcode]Word Break单词切分
- 单词切分-LintCode
- [LintCode 107] 单词切分(Python)
- lintcode(107)单词切分
- lintcode:单词切分
- lintcode-107-单词切分
- LintCode 单词切分
- LintCode:M-单词切分
- Lintcode--009(单词切分)
- 最后一个单词的长度 -LintCode
- [LintCode] 最长单词
- 单词表示数字-LintCode
- LintCode 133 最长单词
- lintcode 最后一个单词的长度(Java)
- 循环单词-LintCode
- LintCode_单词接龙
- Lintcode最长单词