#1813
Medium Algorithms Sentence similarity iii
Array Two Pointers String
48.5% acceptance
Feb 25, 2026
1064
163
You are given two strings sentence1 and sentence2, each representing a sentence composed of words.
A sentence is a list of words that are separated by a single space with no leading or trailing spaces.
Each word consists of only uppercase and lowercase English characters.
Two sentences s1 and s2 are considered similar if it is possible to insert an arbitrary sentence (possibly empty) inside one of these sentences such that the two sentences become equal.
Note that the inserted sentence must be separated from existing words by spaces.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn are_sentences_similar(sentence1: String, sentence2: String) -> bool {
let w1: Vec<&str> = sentence1.split_whitespace().collect();
let w2: Vec<&str> = sentence2.split_whitespace().collect();
let (long, short) = if w1.len() >= w2.len() { (&w1, &w2) } else { (&w2, &w1) };
let n = long.len();
let m = short.len();
// match from front
let mut front = 0;
while front < m && long[front] == short[front] {
front += 1;
}
// match from back
let mut back = 0;
while back < m - front && long[n - 1 - back] == short[m - 1 - back] {
back += 1;
}
front + back >= m
}
}