LeetCode Word Break

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.

For example, given
s = "leetcode",
dict = ["leet", "code"].

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

题意:给定一个字符串和一个单词表,找出字符串是否能由单词表拼接而成。

需要注意点:baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

['a','aa','aaa','aaaaa'...‘aaaaaaaaa’]可能出现超时。

 

使用DP解决,

public boolean wordBreak(String s, Set<String> dict) {
		if (s == null || s.length() == 0)
			return false;
		else if (dict.contains(s))
			return true;

		List<Integer> starts = new LinkedList<Integer>();
		starts.add(0);

		for (int end = 1; end <= s.length(); end++) {
			boolean found = false;
			for (Integer start : starts)
				if (dict.contains(s.substring(start, end))) {
					System.out.println(s.substring(start, end));
					found = true;
					break;
				}
			if (found)
				starts.add(0, end);
		}

		return (starts.get(0) == s.length());
	}

 测试:

 

	String s = "leetcodealeetcode";
		Set<String> set = new HashSet<String>();
		set.add("leetc");
		set.add("odea");
		set.add("leet");
		set.add("code");
		WordBreak wordBreak = new WordBreak();
		boolean t = wordBreak.wordBreak(s, set);
		System.out.println(t);

 

 

 

你可能感兴趣的:(LeetCode)