【leetcode】No.139:word-break-Ⅰ

题目描述

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

input:

s ="leetcode",
dict =["leet", "code"]

output:

Return true because"leetcode"can be segmented as"leet code"

思路:

新建一个n+1长度boolean数组flag,flag[i]=true表明s[i]之前的字符串可以由字典里的词组合,显然flag[0]=true,然后遍历字符串,遍历到s[i]时使用j去遍历s[i]之前字符串的每一位,如果flag[j]=true并且s[j]到s[i]之间的子串在字典中,则说明flag[i]也应该为true,遍历完字符串后返回flag[n]的值就是答案

代码:

import java.util.Set;

public class Solution {
    public boolean wordBreak(String s, Set dict) {
        int len = s.length();
        boolean[] flags = new boolean[len + 1];
        flags[0] = true;
        for (int i = 1; i <= len; i++){
            for (int j = 0; j < i; j++){
                if (flags[j] && dict.contains(s.substring(j, i))){
                    flags[i] = true;
                    break;
                }
            }
        }
        return flags[len];
    }
}

你可能感兴趣的:(【leetcode】No.139:word-break-Ⅰ)