Sentence Similarity III

medium two pointers string array

Problem

You are given two sentences sentence1 and sentence2, each a string of space-separated words. The two sentences are similar if it is possible to insert one extra sentence (which may be empty) into exactly one of them — at the start, the end, or between two words — so that the two become identical.

Note that the inserted block must be a single contiguous run of words; you may not sprinkle words into several different places. Return true if the sentences are similar and false otherwise.

Inputsentence1 = "My name is Haley", sentence2 = "My Haley"
Outputtrue
Insert "name is" into sentence2 between "My" and "Haley" and it becomes "My name is Haley", which equals sentence1. The shared prefix "My" and shared suffix "Haley" already cover every word of the shorter sentence.

def are_sentences_similar(sentence1, sentence2):
    a = sentence1.split()
    b = sentence2.split()
    i, j = 0, 0
    n, m = len(a), len(b)
    while i < n and i < m and a[i] == b[i]:
        i += 1
    while j < n - i and j < m - i and a[n - 1 - j] == b[m - 1 - j]:
        j += 1
    return i + j >= min(n, m)
function areSentencesSimilar(sentence1, sentence2) {
  const a = sentence1.split(" ");
  const b = sentence2.split(" ");
  let i = 0, j = 0;
  const n = a.length, m = b.length;
  while (i < n && i < m && a[i] === b[i]) i++;
  while (j < n - i && j < m - i && a[n - 1 - j] === b[m - 1 - j]) j++;
  return i + j >= Math.min(n, m);
}
class Solution {
    public boolean areSentencesSimilar(String sentence1, String sentence2) {
        String[] a = sentence1.split(" ");
        String[] b = sentence2.split(" ");
        int i = 0, j = 0;
        int n = a.length, m = b.length;
        while (i < n && i < m && a[i].equals(b[i])) i++;
        while (j < n - i && j < m - i && a[n - 1 - j].equals(b[m - 1 - j])) j++;
        return i + j >= Math.min(n, m);
    }
}
bool areSentencesSimilar(string sentence1, string sentence2) {
    vector<string> a = split(sentence1), b = split(sentence2);
    int i = 0, j = 0;
    int n = a.size(), m = b.size();
    while (i < n && i < m && a[i] == b[i]) i++;
    while (j < n - i && j < m - i && a[n - 1 - j] == b[m - 1 - j]) j++;
    return i + j >= min(n, m);
}
Time: O(n + m) Space: O(n + m)