-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdaily128.java
More file actions
41 lines (35 loc) · 1.01 KB
/
Copy pathdaily128.java
File metadata and controls
41 lines (35 loc) · 1.01 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
// Solution 1
class Solution {
public int isPrefixOfWord(String sentence, String searchWord) {
/*
split string into word array
match characters until we find the right prefix
*/
String[] words = sentence.split("\\s+");
for (int i = 0; i < words.length; i++) {
String w = words[i];
int w_idx = 0;
int s_idx = 0;
while (s_idx < searchWord.length() && w_idx < w.length()) {
if (w.charAt(w_idx) != searchWord.charAt(s_idx))
break;
s_idx++;
w_idx++;
}
if (s_idx == searchWord.length())
return i + 1;
}
return -1;
}
}
// Solution 2
class Solution {
public int isPrefixOfWord(String sentence, String searchWord) {
String arr[]=sentence.split(" ");
for(int i=0;i<arr.length;i++){
if(arr[i].startsWith(searchWord))
return i+1;
}
return -1;
}
}