LeetCode 5706. 句子相似性 III

el/2023/6/3 16:53:29

文章目录

    • 1. 题目
    • 2. 解题

1. 题目

一个句子是由一些单词与它们之间的单个空格组成,且句子的开头和结尾没有多余空格。
比方说,"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 中的单词都只由单个空格隔开。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sentence-similarity-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • 切分出单词,在长的 list 的两端,遍历找 短的 list,短的能全部被找到即可
class Solution:def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool:	s1 = sentence1.split(' ');s2 = sentence2.split(' ');n1 = len(s1)n2 = len(s2)if n1 > n2:s1, s2 = s2, s1n1, n2 = n2, n1i = 0j = n2-1k = 0g = n1-1count = 0while k < n1:if s1[k] == s2[i]:k += 1i += 1count += 1else:break;while k <= g:if s1[g] == s2[j]:g -= 1j -= 1count += 1else:break;return count == n1

44 ms 15 MB Python3


我的CSDN博客地址 https://michael.blog.csdn.net/

长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!
Michael阿明

http://www.ngui.cc/el/413294.html

相关文章

《Everything快速搜索文件工具》

是不是觉得微软自带的搜索工具太慢了&#xff0c;别急&#xff0c;给你推荐一款快速好用的文件搜索工具Everything&#xff0c;一秒钟时间都用不到。 官网下载 官网下载链接&#xff1a;http://www.voidtools.com/downloads/ 对于英文菜的抠脚的同学&#xff0c;推荐多种语言的…

《MFC如何添加EXCEL库和操作EXCEL》

EXCEL工作簿、工作表、单元格、行、列 我们在使用EXCEL时&#xff0c;需要搞清楚EXCEL应用程序、工作簿、工作表以及单元格的关系&#xff0c;还有如何设置字体和背景以及边框的属性。总之&#xff0c;就是1个工作簿&#xff08;workbook&#xff09;中含有很多个工作表&#…