GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode/code/lc139.java at master · mJackie/leetcode Expand file tree/ Copy pathlc139.javaMore file actions 39 lines (37 loc) · 1.29 KB / Copy pathlc139.javaFile metadata and controls39 lines (37 loc) · 1.29 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 package code; /* * 139. Word Break * 题意:是否能够分词 * 难度:Medium * 分类:Dynamic Programming * 思路:动态规划 * Tips:巧妙的方法,防止了复杂的操作,通过遍历之前计算出来的结果 * 递归的方法本质和dp是一样的,记住用备忘录算法,把之前的结果记下来 * lc140 */ import java.util.HashMap; import java.util.List; public class lc139 { public boolean wordBreak(String s, List<String> wordDict) { boolean[] dp = new boolean[s.length()+1]; dp[0] = true; for (int i = 1; i < dp.length ; i++) { for (int j = 0; j < i ; j++) { //遍历之前计算出来的结果 if( dp[j]==true && wordDict.contains(s.substring(j,i))) dp[i] = true; } } return dp[s.length()]; } HashMap<String, Boolean> hm = new HashMap(); public boolean wordBreak2(String s, List<String> wordDict) { if(hm.containsKey(s)) return hm.get(s); if(s.length() == 0) return true; Boolean flag = false; for(String word:wordDict){ if(s.startsWith(word)) flag = flag||wordBreak(s.substring(word.length()), wordDict); //注意函数 startsWith } hm.put(s, flag); return flag; } } |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |