-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathReplaceWords.java
78 lines (53 loc) · 1.57 KB
/
ReplaceWords.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
Source: https://leetcode.com/problems/replace-words/
Approach 1 (Brute force)
Time: O(m * n), where m is the length of the given string(sentence) and n is the length of list(dictionary)
Space: O(n), StringBuilder is needed to store the words
*/
class Solution {
public String replaceWords(List<String> dictionary, String sentence) {
String[] split = sentence.split(" ");
StringBuilder res = new StringBuilder();
for(String word : split) {
for(String root : dictionary) {
if(word.startsWith(root)) {
word = root;
}
}
if(res.length() != 0) {
res.append(' ');
}
res.append(word);
}
return res.toString();
}
}
/*
Approach 2 (Without using split())
Time: O(m * n), where m is the length of the given string(sentence) and n is the length of list(dictionary)
Space: O(n), StringBuilder is needed to store the words
*/
class Solution {
public static String replaceWords(List<String> dictionary, String sentence) {
StringBuilder res = new StringBuilder();
char[] sentenceChars = sentence.toCharArray();
int len = sentence.length();
for(int i = 0; i < len; ++i) {
int firstIndex = i;
while(i < len && sentenceChars[i] != ' ') {
++i;
}
String word = String.valueOf(sentenceChars, firstIndex, i - firstIndex);
for(String root : dictionary) {
if(word.startsWith(root)) {
word = root;
}
}
if(res.length() != 0) {
res.append(' ');
}
res.append(word);
}
return res.toString();
}
}