File tree Expand file tree Collapse file tree 2 files changed +68
-0
lines changed
src/main/java/com/algorithm/shoppe Expand file tree Collapse file tree 2 files changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .algorithm .shoppe ;
2
+
3
+ /**
4
+ * @author shenli
5
+ * @date 2021/12/13
6
+ */
7
+ public class MoveZeroes {
8
+
9
+ public void moveZeroes (int [] nums ) {
10
+ int n = nums .length ;
11
+ int left =0 ;
12
+ int right = 0 ;
13
+ while (right <n ) {
14
+ if (nums [right ] !=0 ) {
15
+ swap (nums ,left ,right );
16
+ left ++;
17
+ }
18
+ right ++;
19
+ }
20
+ }
21
+
22
+ public void swap (int [] nums , int left , int right ) {
23
+ int temp = nums [left ];
24
+ nums [left ] = nums [right ];
25
+ nums [right ] = temp ;
26
+ }
27
+ }
Original file line number Diff line number Diff line change
1
+ package com .algorithm .shoppe ;
2
+
3
+ import java .util .HashSet ;
4
+ import java .util .List ;
5
+ import java .util .Set ;
6
+
7
+ /**
8
+ * @author shenli
9
+ * @date 2021/12/13
10
+ */
11
+ public class WordBreak {
12
+
13
+ /**
14
+ * 时间复杂度:O(n^2)O(n
15
+ * 2
16
+ * ) ,其中 nn 为字符串 ss 的长度。我们一共有 O(n)O(n) 个状态需要计算,每次计算需要枚举 O(n)O(n) 个分割点,哈希表判断一个字符串是否出现在给定的字符串列表需要 O(1)O(1) 的时间,因此总时间复杂度为 O(n^2)O(n
17
+ * 2
18
+ * )。
19
+ *
20
+ * 空间复杂度:O(n)O(n) ,其中 nn 为字符串 ss 的长度。我们需要 O(n)O(n) 的空间存放 \textit{dp}dp 值以及哈希表亦需要 O(n)O(n) 的空间复杂度,因此总空间复杂度为 O(n)O(n)。
21
+ *
22
+ * @param s
23
+ * @param wordDict
24
+ * @return
25
+ */
26
+ public boolean wordBreak (String s , List <String > wordDict ) {
27
+ Set <String > wordDictSet = new HashSet <>(wordDict );
28
+ boolean [] dp = new boolean [s .length () + 1 ];
29
+ dp [0 ] = true ;
30
+ for (int i = 1 ; i < s .length (); i ++) {
31
+ for (int j = 0 ; j < i ; j ++) {
32
+ if (dp [j ] && wordDictSet .contains (s .substring (j , i ))) {
33
+ dp [i ] = true ;
34
+ break ;
35
+ }
36
+ }
37
+ }
38
+ return dp [s .length ()];
39
+
40
+ }
41
+ }
You can’t perform that action at this time.
0 commit comments