[LeetCode] 1813. Sentence Similarity III

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.

Example 1:

Input: sentence1 = "My name is Haley", sentence2 = "My Haley"
Output: true
Explanation: sentence2 can be turned to sentence1 by inserting "name is" between "My" and "Haley".

Example 2:

Input: sentence1 = "of", sentence2 = "A lot of words"
Output: false
Explanation: No single sentence can be inserted inside one of the sentences to make it equal to the other.

Example 3:

Input: sentence1 = "Eating right now", sentence2 = "Eating"
Output: true
Explanation: sentence2 can be turned to sentence1 by inserting "right now" at the end of the sentence.

Constraints:

  • 1 <= sentence1.length, sentence2.length <= 100
  • sentence1 and sentence2 consist of lowercase and uppercase English letters and spaces.
  • The words in sentence1 and sentence2 are separated by a single space.

句子相似性 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 。

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

思路是用两个双端队列分别存储 sentence1 和 sentence2,然后根据队列左端和右端单词是否相同决定是否要从队列中弹出。最后判断这两个双端队列其中是不是有一个队列为空,为空的那个就是长度较短的 sentence。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public boolean areSentencesSimilar(String sentence1, String sentence2) {
 3         Deque<String> dq1 = new ArrayDeque<>(Arrays.asList(sentence1.split(" ")));
 4         Deque<String> dq2 = new ArrayDeque<>(Arrays.asList(sentence2.split(" ")));
 5         while (!dq1.isEmpty() && !dq2.isEmpty() && dq1.peekFirst().equals(dq2.peekFirst())) {
 6             dq1.pollFirst();
 7             dq2.pollFirst();
 8         }
 9         while (!dq1.isEmpty() && !dq2.isEmpty() && dq1.peekLast().equals(dq2.peekLast())) {
10             dq1.pollLast();
11             dq2.pollLast();
12         }
13         return dq1.isEmpty() || dq2.isEmpty();
14     }
15 }

 

LeetCode 题目总结

posted @ 2023-01-16 06:20  CNoodle  阅读(39)  评论(0编辑  收藏  举报