句子相似性 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
sentence1andsentence2are 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
sentence1andsentence2, returntrueifsentence1andsentence2are 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)
- 复杂度

该问题涉及字符串处理,要求判断两个句子是否可以通过在其中一个句子中插入任意句子(可能为空)变得相等。提供的解决方案是通过分割句子成单词,然后比较两边相同单词的数量,如果两边相等则返回true,否则返回false。
16万+

被折叠的 条评论
为什么被折叠?



