-
Notifications
You must be signed in to change notification settings - Fork 0
/
LC2109.java
48 lines (37 loc) · 1.03 KB
/
LC2109.java
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
40
41
42
43
44
45
46
47
48
// problem: 2109. Adding Spaces to a String
// difficulty: medium
// time complexity: O(n)
// space complexity: O(n)
class Solution {
public String addSpaces(String s, int[] spaces) {
StringBuilder sb = new StringBuilder();
int i = 0;
int j = 0;
for (i = 0; i < spaces.length; i++) {
j = i == 0 ? 0 : spaces[i-1];
sb.append(s,j,spaces[i]);
sb.append(' ');
}
sb.append(s.substring(spaces[i-1]));
return sb.toString();
}
}
// version 1.0
class Solution {
public String addSpaces(String s, int[] spaces) {
StringBuilder sb = new StringBuilder();
int i=0;
int j=0;
for (i = 0; i < spaces.length; i++) {
j = i == 0 ? 0 : spaces[i-1];
for (; j < spaces[i]; j++) {
sb.append(s.charAt(j));
}
sb.append(' ');
}
for (; j < s.length(); j++) {
sb.append(s.charAt(j));
}
return sb.toString();
}
}