题解 | #拆分词句#

拆分词句

https://www.nowcoder.com/practice/5f3b7bf611764c8ba7868f3ed40d6b2c

从前往后通过int i遍历遍历, 看看前i个是否能分割后被字典找到, 假如可以就设置i下标的boolean值为true, 这个boolean值可以被后面的遍历所利用, 相当于记录下了之前的结果.
import java.util.Set;

public class Solution {
    public boolean wordBreak(String s, Set<String> dict) {
        if (dict.isEmpty()) {
            return false;
        }

        //true表示前index个单词都是可以被分割后被字典查到的
        boolean[] canBreak = new boolean[s.length() + 1];
        canBreak[0] = true;

        for (int i = 1; i < s.length() + 1; i++) {
            for (int j = i - 1; j >= 0; j--) {
                //前j个可分割, 然后j~i可找到, 所以i可分割
                if (canBreak[j] && dict.contains(s.substring(j, i))) {
                    canBreak[i] = true;
                    break;
                }
            }
        }
        return canBreak[s.length()];
    }
}



全部评论

相关推荐

双非本科小鼠:27兄弟,不应该还在享受校园吗哈哈😂
点赞 评论 收藏
分享
vip牛牛:测试吧,开发现在至少212
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务