-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathsolution.java
36 lines (29 loc) · 1.03 KB
/
solution.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
class Solution {
// Helper function to split a sentence into words
private String[] splitWords(String sentence) {
return sentence.split(" ");
}
public boolean areSentencesSimilar(String sentence1, String sentence2) {
// Split both sentences into arrays of words
String[] words1 = splitWords(sentence1);
String[] words2 = splitWords(sentence2);
// Ensure words1 is the longer sentence
if (words1.length < words2.length) {
String[] temp = words1;
words1 = words2;
words2 = temp;
}
int start = 0, end = 0;
int n1 = words1.length, n2 = words2.length;
// Compare from the start
while (start < n2 && words1[start].equals(words2[start])) {
start++;
}
// Compare from the end
while (end < n2 && words1[n1 - end - 1].equals(words2[n2 - end - 1])) {
end++;
}
// Check if the remaining unmatched part is in the middle
return start + end >= n2;
}
}