classSolution: defareSentencesSimilar(self, sentence1: str, sentence2: str) -> bool: words1 = sentence1.split() words2 = sentence2.split() i, j = 0, 0 while i < len(words1) and i < len(words2) and words1[i] == words2[i]: i += 1 while j < len(words1) - i and j < len(words2) - i and words1[-j - 1] == words2[-j - 1]: j += 1 return i + j == min(len(words1), len(words2))
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { publicbooleanareSentencesSimilar(String sentence1, String sentence2) { String[] words1 = sentence1.split(" "); String[] words2 = sentence2.split(" "); inti=0, j = 0; while (i < words1.length && i < words2.length && words1[i].equals(words2[i])) { i++; } while (j < words1.length - i && j < words2.length - i && words1[words1.length - j - 1].equals(words2[words2.length - j - 1])) { j++; } return i + j == Math.min(words1.length, words2.length); } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicclassSolution { publicboolAreSentencesSimilar(string sentence1, string sentence2) { string[] words1 = sentence1.Split(newchar[]{' '}); string[] words2 = sentence2.Split(newchar[]{' '}); int i = 0, j = 0; while (i < words1.Length && i < words2.Length && words1[i].Equals(words2[i])) { i++; } while (j < words1.Length - i && j < words2.Length - i && words1[words1.Length - j - 1].Equals(words2[words2.Length - j - 1])) { j++; } return i + j == Math.Min(words1.Length, words2.Length); } }