[LeetCode] Sentence Similarity III

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
fun areSentencesSimilar(sentence1: String, sentence2: String): Boolean {
val token1 = sentence1.split(' ').toMutableList()
val token2 = sentence2.split(' ').toMutableList()

return if(token1.size > token2.size) isSimilar(token2, token1) else isSimilar(token1, token2)
}

private fun isSimilar(token1: MutableList<String>, token2: MutableList<String>): Boolean {
while(token1.isNotEmpty() && token1.last() == token2.last()) {
token1.removeAt(token1.lastIndex)
token2.removeAt(token2.lastIndex)
}

while(token1.isNotEmpty() && token1.first() == token2.first()) {
token1.removeAt(0)
token2.removeAt(0)
}

return token1.isEmpty()
}
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/21/PS/LeetCode/sentence-similarity-iii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.