动态规划:word-break

来源:互联网 发布:时间浪人网络大电影 编辑:程序博客网 时间:2024/05/28 03:03

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”.

析:给你一个单词,判断它是否可以分割开来,每个分割体是右面集合中的元素。
思路:用一个List存储下标,表中条件为满足:从i到单词的最末之间的子串是右边集合中的,
判断(j,last)是否为true,如果子串(j,last)直接在子串中,把j加入到List,如果不在,判断当前List中是否存在i,使得子串(j,i)和(i,last)都在集合中,如果有说明j也满足条件。

总体思路:从右向左动态规划。

public boolean wordBreak(String s, Set<String> dict) {        int n = s.length();        List<Integer> indexList = new ArrayList<>();        for(int i=n-1;i>=0;i--){            if(dict.contains(s.substring(i)))                indexList.add(i);            else            for(Integer t:indexList){                if(dict.contains(s.substring(i,t))){                    indexList.add(i);                    break;                }            }        }        return indexList.contains(0);    }
原创粉丝点击