139. Word Break
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
For example, given
s = "leetcode"
,
dict = ["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet code"
.
UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
也是一題dp,但是因為我想不到怎麼拆解所以最後還是看討論
基本上就是 i 是否有word 是由所有之前可構成的word + 剩下的是否是word 來決定
ex. leetcode 是否是word = leet 是否是word字 && 剩下的word 是否是word構成
所以反例就是 leetcod = leet 是單字, but 剩下的 cod 不是word 所以為否
或者 lee 不是單字 (後面就也不用看了)
這樣由小拼圖街成大拼圖完成,本來想得太複雜,還想用 Floyd 但是其實不用,這樣找不到所謂的規則性
class Solution { public boolean wordBreak(String s, List<String> wordDict) { HashSet<String> set = new HashSet(); for(String word: wordDict) set.add(word); boolean[] word_list = new boolean[s.length()+1]; word_list[0] = true; for(int i=1; i<= s.length(); i++){ for(int j=0; j < i; j++){ if(word_list[j] && set.contains(s.substring(j,i))) { word_list[i] = true; break; } } } return word_list[s.length()]; } }
238. Product of Array Except Self
Given an array of n integers where n > 1, nums
, return an array output
such that output[i]
is equal to the product of all the elements of nums
except nums[i]
.
Solve it without division and in O(n).
For example, given [1,2,3,4]
, return [24,12,8,6]
.
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
這題自己有想到概念,但是找不到漂亮的implementation,在這邊基本上就是用右邊連乘,然後搭配左邊連乘,就可以算出結果了
加上要用 O(1) extra space (not include result array )
先把left_m array 聯乘值存入result array ,然後對稱做,不過這次不要去令一個 right_m array ,因為只會用到值,所以用個integer 紀錄就好了
class Solution { public int[] productExceptSelf(int[] nums) { int len = nums.length, right=1; int[] res = new int[len]; res[0] = 1; for(int index=1; index < len; index++) res[index] = res[index-1] * nums[index-1]; for(int index = len-1; index>=0; index--){ res[index] *= right; right *= nums[index]; } return res; } }
留言列表