美文网首页
139. 单词拆分

139. 单词拆分

作者: Abeants | 来源:发表于2022-03-19 09:40 被阅读0次

给你一个字符串 s 和一个字符串列表 wordDict 作为字典。请你判断是否可以利用字典中出现的单词拼接出 s 。

注意:不要求字典中出现的单词全部都使用,并且字典中的单词可以重复使用。

示例 1:
输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以由 "leet" 和 "code" 拼接成。

示例 2:
输入: s = "applepenapple", wordDict = ["apple", "pen"]
输出: true
解释: 返回 true 因为 "applepenapple" 可以由 "apple" "pen" "apple" 拼接成。
注意,你可以重复使用字典中的单词。

示例 3:
输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
输出: false

提示:
1 <= s.length <= 300
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 20
s 和 wordDict[i] 仅有小写英文字母组成
wordDict 中的所有字符串 互不相同

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-break
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路及方法

最开始我想的是截取字符串模拟,但是遇到类似这种情况["car", "ca", "rs"],s="cars",就会先截取字符串"car",剩下"s"wordDict里没有,便返回false。

public class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        int n = s.length();
        // 记录已拼接长度
        int cntLen = 0;
        String cur = s;

        while (cur.length() != 0) {
            // 记录当前长度
            int curLen = cur.length();
            // 逐个比较
            for (String str : wordDict) {
                int len = str.length();
                // 判断字典内字符串是否可以组成s
                if (len > cur.length()) continue;
                if (cur.substring(0, len).equals(str)) {
                    cntLen += len;
                    cur = s.substring(cntLen, n);
                    System.out.println(cur);
                    break;
                }
            }
            // 如果字典内字符串不能组成s,即剩余字符串无变化
            if (cur.length() == curLen) return false;
        }

        return true;
    }
}

前面方法是错误的,我看了题解,用动态规划做,很巧妙,看这里

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        int n = s.length();
        boolean[] dp = new boolean[n + 1];
        dp[0] = true;

        for (int i = 1; i <= n; i++) {
            for (int j = 0; j < i; j++) {
                // 判断字符串前i个字符能否由wordDict内单词组成
                if (dp[j] && wordDict.contains(s.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }

        return dp[n];
    }
}

结果如下:

相关文章

网友评论

      本文标题:139. 单词拆分

      本文链接:https://www.haomeiwen.com/subject/busgdrtx.html