Sponsored
Sponsored
The Two Pointers technique involves using two indices that move towards each other from the start and end of the lists. This approach effectively captures the prefixes and suffixes.
By using two pointers, we move from the start to the first words that don't match and from the end to the first words that also don't match. If the pointers end up crossing or are equal, the sentences are considered similar. We exploit the fact that any dissimilar portion in the middle, if any, can be 'inserted'.
Time Complexity: O(n + m), where n and m are the lengths of sentence1 and sentence2 respectively.
Space Complexity: O(n + m) for storing words.
1using System;
2
3public class Solution {
4 public bool AreSentencesSimilar(string sentence1, string sentence2) {
5 string[] s1_words = sentence1.Split(' ');
6 string[] s2_words = sentence2.Split(' ');
7
8 int i = 0, j = 0;
9
10 while (i < s1_words.Length && i < s2_words.Length && s1_words[i] == s2_words[i]) {
11 i++;
12 }
13
14 while (j < s1_words.Length - i && j < s2_words.Length - i &&
15 s1_words[s1_words.Length - j - 1] == s2_words[s2_words.Length - j - 1]) {
16 j++;
17 }
18
19 return (i + j >= s1_words.Length || i + j >= s2_words.Length);
20 }
21}
22
C# utilizes String.Split
to create arrays from sentences, and twin counter mechanisms to iterate through these arrays for potential word matches.
Another approach is to utilize a dynamic programming table to store sub-problems results. You can construct a DP table where dp[i][j]
indicates whether the first i
words from sentence1
can match the first j
words from sentence2
. This could be expanded using insertion strategies for any non-matching sub-sequences.
This approach relies more on systematic computation than geometric traversal, but can be more memory intensive.
Time Complexity: O(n*m)
Space Complexity: O(n*m)
1
public class Solution {
public bool AreSentencesSimilar(string sentence1, string sentence2) {
string[] s1_words = sentence1.Split(' ');
string[] s2_words = sentence2.Split(' ');
bool[,] dp = new bool[s1_words.Length + 1, s2_words.Length + 1];
dp[0, 0] = true;
for (int i = 0; i <= s1_words.Length; i++) {
for (int j = 0; j <= s2_words.Length; j++) {
if (i > 0 && j > 0 && s1_words[i-1] == s2_words[j-1]) {
dp[i, j] = dp[i-1, j-1];
}
else if (i > 0) {
dp[i, j] = dp[i-1, j] || dp[i, j];
}
else if (j > 0) {
dp[i, j] = dp[i, j-1] || dp[i, j];
}
}
}
return dp[s1_words.Length, s2_words.Length];
}
}
In C#, the DP matrix is handled using a two-dimensional boolean array, with loops used to determine matching possibilities or strategic insertions.