Word Break LeetCode

来源:互联网 发布:淘宝店铺首页设计尺寸 编辑:程序博客网 时间:2024/06/10 01:08
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"].


public class Solution {    public boolean wordBreak(String s, Set<String> dict) {        ArrayList<Integer> list = new ArrayList<Integer>();        for (int i = s.length() - 1; i >= 0; i--){            String sub = s.substring(i);            if (dict.contains(sub)){                list.add(i);            }else {                for (Integer index : list){                    sub = s.substring(i, index);                    if (dict.contains(sub)){                        list.add(i);                        break;//刚开始的时候把这个漏掉了,会造成很奇怪的事情发生,因为这个时候list的内容发生变化了                    }                }                             }        }        if (list.size() == 0){            return false;        }        return list.get(list.size() - 1) == 0;    }}


0 0
原创粉丝点击