【每日一题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) O(n+m)
      • 空间复杂度: O ( n + m ) O(n+m) O(n+m)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值