当前位置: 首页 > news >正文

【每日一题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)

相关文章:

  • 山西手机版建站系统信息/大数据培训机构排名前十
  • 浏览器推广怎么做/seo长尾快速排名
  • 茂名网站制作推广/网站快速排名推荐
  • 网站开发用的是什么语言/西安百度竞价推广
  • 杭州设计公司网站排名/安卓优化大师2021
  • 杭州网站建设公司代理加盟/荆州seo推广
  • 学习记录661@项目管理之项目立项管理
  • 手工测试 | 黑盒测试方法论—边界值
  • 【云原生】k8s安全机制
  • LeetCode刷题模版:111 - 120
  • 从头安装gdal库(Linux环境下的Python版)
  • 【sklearn】GradientBoosting(GBDT)
  • 【C++】Hash闭散列
  • 字符读写文件流
  • 【学习笔记】【Pytorch】张量(Tensor)的基础操作
  • 【C++升级之路】第七篇:STL简介
  • Servlet —— Smart Tomcat,以及一些访问出错可能的原因
  • 嵌入式linux-进程状态与进程关系