1813. Sentence Similarity III
UnknownView on LeetCode
Time: O(n)
Space: O(n)
Problem Overview
Sentence Similarity III (Unknown) asks you to solve a structured algorithmic task. This is a common Two Pointers / String pattern in coding interviews. Split into word arrays; match common prefix and suffix with two pointers; check if shorter is covered.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Split into word arrays; match common prefix and suffix with two pointers; check if shorter is covered.
Related patterns: Two Pointers, String
1813.cs
C#
// Approach: Split into word arrays; match common prefix and suffix with two pointers; check if shorter is covered.
// Time: O(n) Space: O(n)
public class Solution
{
public bool AreSentencesSimilar(string sentence1, string sentence2)
{
if (sentence1.Length == sentence2.Length)
return sentence1.Equals(sentence2);
string[] words1 = sentence1.Split(' ');
string[] words2 = sentence2.Split(' ');
int m = words1.Length;
int n = words2.Length;
if (m > n)
return AreSentencesSimilar(sentence2, sentence1);
int i = 0; // words1's index
while (i < m && words1[i].Equals(words2[i]))
++i;
while (i < m && words1[i].Equals(words2[i + n - m]))
++i;
return i == m;
}
}Was this solution helpful?
Related Problems
- 11. Container With Most Water(Medium)
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 14. Longest Common Prefix(Easy)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)