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

【LeetCode】1813. 句子相似性 III

1813. 句子相似性 III

题目描述

一个句子是由一些单词与它们之间的单个空格组成,且句子的开头和结尾没有多余空格。比方说,“Hello World” ,“HELLO” ,“hello world hello world” 都是句子。每个单词都 只 包含大写和小写英文字母。

如果两个句子 sentence1 和 sentence2 ,可以通过往其中一个句子插入一个任意的句子(可以是空句子)而得到另一个句子,那么我们称这两个句子是 相似的 。比方说,sentence1 = “Hello my name is Jane” 且 sentence2 = “Hello Jane” ,我们可以往 sentence2 中 “Hello” 和 “Jane” 之间插入 “my name is” 得到 sentence1 。

给你两个句子 sentence1 和 sentence2 ,如果 sentence1 和 sentence2 是相似的,请你返回 true ,否则返回 false 。


示例 1

输入:sentence1 = “My name is Haley”, sentence2 = “My Haley”
输出:true
解释:可以往 sentence2 中 “My” 和 “Haley” 之间插入 “name is” ,得到 sentence1 。


示例 2

输入:sentence1 = “of”, sentence2 = “A lot of words”
输出:false
解释:没法往这两个句子中的一个句子只插入一个句子就得到另一个句子。


示例 3

输入:sentence1 = “Eating right now”, sentence2 = “Eating”
输出:true
解释:可以往 sentence2 的结尾插入 “right now” 得到 sentence1 。


示例 4

输入:sentence1 = “Luky”, sentence2 = “Lucccky”
输出:false


提示

  • 1 <= sentence1.length, sentence2.length <= 100
  • sentence1 和 sentence2 都只包含大小写英文字母和空格。
  • sentence1 和 sentence2 中的单词都只由单个空格隔开。

算法一:双指针 + stringstream 字符串分割

思路

  • 分析题目得到插入的句子必定是 中间的句子, 我们先用空格将句子分割成若干个字符串,然后使用双指针,分别统计两个句子左边相等的单词数,右边相等的单词数,如果两边相等的单词数加起来等于子句的单词数,说明可以在子句中插入一个句子得到长句。
  • 需要保证 sentence1 一定是长句, sentence2 一定是短句,便于处理。【我是比较两个字符串长度,然后交换;题解直接使用 return 交换两个字符串】

收获

  • stringstream 分割包含空格的字符串,具体用法见参考资料1 ;
  • 为了确保 sentence2 是被插入的句子,可以通过 return areSentencesSimilar(sentence2, sentence1) 交换两个句子;

算法情况

  • 时间复杂度:O(m+n),其中 m 是 sentence1 的单词数,n 是 sentence2 的单词数。
  • 空间复杂度:O(m+n)

代码

class Solution {
public:
    vector<string> split(string s){
        vector<string> ans;
        stringstream ss(s);
        // ss << s; 初始化 与上句作用相等
        while(ss >> s) ans.push_back(s);
        return ans;
    }
    bool areSentencesSimilar(string sentence1, string sentence2) {
        // sentence1 长句 sentence2 短句
        if(sentence1.size() < sentence2.size()) return areSentencesSimilar(sentence2, sentence1);
        int l = 0, r = 0;
        // 单词分割
        vector<string> word1, word2;
        word1 = split(sentence1);
        word2 = split(sentence2);
        int m = word1.size(), n = word2.size();
        while(l < n && word1[l] == word2[l]) l++;
        while(r < n - l && word1[m-r-1] == word2[n-r-1]) r++;
        return l + r == n;
    }
};

参考资料

  1. stringstream用法

相关文章:

  • Xilinx 7系列FPGA之Spartan-7产品简介
  • 【机器学习之模型融合】Stacking堆叠法
  • 试题 基础练习 完美的代价
  • 【自学Python】Python字符串出现次数
  • 2-求和(蓝桥杯)
  • (一)Jenkins部署、基础配置
  • 2022考研人年度总结,描摹23实习备战进行时
  • W13Scan 漏洞扫描器之XSS插件模块编写示例
  • 开发微信小程序过程中遇到的问题笔记
  • 冒泡排序算法的实现和优化~
  • JAVA练习21
  • 我的 git 实战记录
  • MongoTemplate 操作 Mongo的字段中List元素
  • Maix Bit(K210)保姆级入门上手教程---外设基本使用
  • 实时即未来,大数据项目车联网之Flink Watermark(水位线)【十四】
  • 好看的滤镜怎么调?来看看今日的分享
  • AppScan介绍和安装
  • 1.13笔记
  • Elasticsearch连续剧之分词器
  • 实战Kaggle比赛:预测房价