LeetCode 1813: Sentence Similarity III Solution

Master LeetCode problem 1813 (Sentence Similarity III), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1813. Sentence Similarity III

Problem Explanation

Explanation:

To solve this problem, we can follow these steps:

  1. Split both sentences into individual words.
  2. Check if either sentence1 is a substring of sentence2 or vice versa. If so, return true.
  3. Iterate through the words of sentence1 and sentence2 simultaneously. If at any point the words differ, we try to find a common prefix and suffix that can be inserted to make the sentences similar.
  4. If no common prefix or suffix is found, return false.

Time complexity: O(n) where n is the maximum length of the two input sentences. Space complexity: O(n) where n is the maximum length of the two input sentences.

:

Solution Code

class Solution {
    public boolean areSentencesSimilar(String sentence1, String sentence2) {
        String[] words1 = sentence1.split(" ");
        String[] words2 = sentence2.split(" ");
        
        if (sentence1.contains(sentence2) || sentence2.contains(sentence1)) {
            return true;
        }
        
        int i = 0, j = 0;
        int m = words1.length, n = words2.length;
        
        while (i < m && j < n && words1[i].equals(words2[j])) {
            i++;
            j++;
        }
        
        while (i < m && j < n && words1[m - 1].equals(words2[n - 1])) {
            m--;
            n--;
        }
        
        return i == m && j == n;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1813 (Sentence Similarity III)?

This page provides optimized solutions for LeetCode problem 1813 (Sentence Similarity III) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1813 (Sentence Similarity III)?

The time complexity for LeetCode 1813 (Sentence Similarity III) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1813 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1813 in Java, C++, or Python.

Back to LeetCode Solutions