【每日一题Day89】LC1813句子相似性 III | 双指针
句子相似性 III【LC1813】
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example,
"Hello World"
,"HELLO"
,"hello world hello world"
are all sentences. Words consist of only uppercase and lowercase English letters.Two sentences
sentence1
andsentence2
are similar if it is possible to insert an arbitrary sentence (possibly empty) inside one of these sentences such that the two sentences become equal. For example,sentence1 = "Hello my name is Jane"
andsentence2 = "Hello Jane"
can be made equal by inserting"my name is"
between"Hello"
and"Jane"
insentence2
.Given two sentences
sentence1
andsentence2
, returntrue
ifsentence1
andsentence2
are similar. Otherwise, returnfalse
.
写了好久空间复杂度O(1)的没写出来
-
思路:由于插入的句子一定插入在字符串的中间(字符串左边或者右边可能为空),因此可以先用空格分隔所有的单词,然后统计左边相等单词的数量,再统计右边相等单词的数量,若两个数量之和等于最小单词数量,那么代表可以向这个字符串中添加一句话使得两个字符串相等
-
实现
class Solution { public boolean areSentencesSimilar(String s1, String s2) { if (s1.length() > s2.length()) return areSentencesSimilar(s2, s1); String[] arr1 = s1.split(" "), arr2 = s2.split(" "); int n = arr1.length, m = arr2.length, l = 0, r = 0; while (l < n && arr1[l].equals(arr2[l])) l++; while (r < n - l && arr1[n - r - 1].equals(arr2[m - r - 1])) r++; return l + r == n; } } 作者:Tizzi 链接:https://leetcode.cn/problems/sentence-similarity-iii/solutions/2064138/javac-shuang-zhi-zhen-by-tizzi-0t5r/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
- 复杂度
- 时间复杂度: O ( n + m ) O(n+m) O(n+m)
- 空间复杂度: O ( n + m ) O(n+m) O(n+m)
- 复杂度