-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution_1813.java
More file actions
63 lines (56 loc) · 2.42 KB
/
Solution_1813.java
File metadata and controls
63 lines (56 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
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 中的单词都只由单个空格隔开。
*/
public class Solution_1813 {
public static void main(String[] args) {
Solution_1813 solution = new Solution_1813();
solution.areSentencesSimilar("hello my name is li", "hello li");
}
public boolean areSentencesSimilar(String sentence1, String sentence2) {
String[] s1 = sentence1.split(" ");
String[] s2 = sentence2.split(" ");
if (s1.length < s2.length) {
String[] temp = s1;
s1 = s2;
s2 = temp;
}
int len1 = s1.length;
int len2 = s2.length;
int l1 = 0, r1 = len1 - 1;
int l2 = 0, r2 = len2 - 1;
while (l2 <= r2 && s1[l1].equals(s2[l2])) {
l1++;
l2++;
}
while (l2 <= r2 && s1[r1].equals(s2[r2])) {
r2--;
r1--;
}
return !(l2 <= r2);
}
}