'动态规划:word-break'

来源:互联网 发布:怎么在淘宝上买账号 编辑:程序博客网 时间:2024/05/19 13:07

题目描述

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.
For example, given
s =”leetcode”,
dict =[“leet”, “code”].
Return true because”leetcode”can be segmented as”leet code”.

解题

import java.util.HashMap;import java.util.HashSet;import java.util.Set;public class Solution {    public  boolean wordBreak(String s, Set<String> dict) {        HashMap<String,Boolean> findString=new HashMap<>();        return dfs(s,findString,dict);    }    public  boolean dfs(String s,HashMap<String,Boolean> hashMap,Set<String> dict){        if (hashMap.containsKey(s)) return hashMap.get(s);        if (s.equals("")){            return true;        }        boolean find=false;        int len=s.length();        for (int i=1;i<=len;i++){            String header=s.substring(0,i);            if (dict.contains(header)){                boolean child=dfs(s.substring(i,s.length()),hashMap,dict);                if (child==true){                    find=true;                    break;                }            }        }        hashMap.put(s,find);        return find;    }}
原创粉丝点击