-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdaily169.java
More file actions
56 lines (46 loc) · 1.18 KB
/
Copy pathdaily169.java
File metadata and controls
56 lines (46 loc) · 1.18 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Solution 1
class Solution {
public String addSpaces(String s, int[] spaces) {
/**
linear approach
make new string
if index == spaces index
add space and then add character
else
keep adding characters
*/
StringBuilder res = new StringBuilder();
int sp_idx = 0;
for (int i = 0; i < s.length(); i++) {
if (sp_idx < spaces.length && i == spaces[sp_idx]) {
res.append(' ');
sp_idx++;
}
res.append(s.charAt(i));
}
return res.toString();
}
}
// Solution 2
class Solution {
public String addSpaces(String s, int[] spaces) {
char[] ch=s.toCharArray();
char[] charr=new char[s.length()+spaces.length];
int idx=0,c=0;
for (int sp:spaces){
while (c<sp){
charr[idx]=ch[c];
idx++;
c++;
}
charr[idx]=' ';
idx++;
}
while(c<s.length()){
charr[idx]=ch[c];
idx++;
c++;
}
return new String(charr);
}
}