1813. Sentence Similarity III
Tags:
Medium
Skills:
StringArray
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Bài toán yêu cầu kiểm tra xem hai câu có thể được coi là “tương tự” hay không. Hai câu được coi là tương tự nếu có thể biến chúng thành giống hệt nhau bằng cách thêm hoặc xóa một số từ từ đầu hoặc cuối của một trong hai câu
Approach
Time and space complexity
Solution
1function areSentencesSimilar(sentence1: string, sentence2: string): boolean {
2 let words1 = sentence1.split(" ");
3 let words2 = sentence2.split(" ")
4
5 if(words1.length < words2.length) {
6 return areSentencesSimilar(sentence2, sentence1)
7 }
8
9 let left = 0;
10 let right = 0;
11
12 while (left < words2.length && words1[left] === words2[left]) {
13 left++;
14 }
15
16 while(right < words2.length &&
17 words1[words1.length - 1 - right] === words2[words2.length - 1 - right]) {
18 right++
19 }
20
21
22 return left + right >= words2.length;
23};