【每日一题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 and sentence2 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" and sentence2 = "Hello Jane" can be made equal by inserting "my name is" between "Hello" and "Jane" in sentence2.


Given two sentences sentence1 and sentence2, return true if sentence1 and sentence2 are similar. Otherwise, return false.


写了好久空间复杂度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 )
目录
相关文章
|
5月前
【每日一题Day369】LC187重复的DNA序列 | 字符串哈希
【每日一题Day369】LC187重复的DNA序列 | 字符串哈希
43 1
|
5月前
【每日一题Day342】LC2578最小和分割 | 贪心
【每日一题Day342】LC2578最小和分割 | 贪心
43 0
|
5月前
【每日一题Day130】LC1255得分最高的单词集合 | 回溯
【每日一题Day130】LC1255得分最高的单词集合 | 回溯
42 0
|
5月前
【每日一题Day150】LC1616分割两个字符串得到回文串 | 双指针+贪心
【每日一题Day150】LC1616分割两个字符串得到回文串 | 双指针+贪心
35 0
|
5月前
【每日一题Day301】LC2337移动片段得到字符串 | 双指针 计分
【每日一题Day301】LC2337移动片段得到字符串 | 双指针 计分
45 0
|
5月前
【每日一题Day302】LC849到最近的人的最大距离 | 贪心+分类讨论
【每日一题Day302】LC849到最近的人的最大距离 | 贪心+分类讨论
53 0
|
4月前
|
算法
【经典LeetCode算法题目专栏分类】【第4期】BFS广度优先算法:单词接龙、最小基因变化、二进制矩阵中的最短路径
【经典LeetCode算法题目专栏分类】【第4期】BFS广度优先算法:单词接龙、最小基因变化、二进制矩阵中的最短路径
|
5月前
【每日一题Day170】LC1040移动石子直到连续 II | 双指针 贪心 数学
【每日一题Day170】LC1040移动石子直到连续 II | 双指针 贪心 数学
45 1
|
算法 测试技术
蓝桥算法_单词分析-wordAnalysis
蓝桥算法_单词分析-wordAnalysis
|
C语言
LeetCode刷题集(四)(LeetCode2114.句子中的最多单词数)
LeetCode刷题集(四)(LeetCode2114.句子中的最多单词数)
55 0