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
andsentence2
consist of lowercase and uppercase English letters and spaces.- The words in
sentence1
andsentence2
are separated by a single space.
题目:给定两个字符串,问能不能在一个字符串中加入一个sentence组成另外一个字符串。
思路:要求只加入一个sentence,则要么加在前面,要么加在后面,要么加在中间。加在前面或后面的时候只需判断后半段或前半段字符串是否相等,注意这里需要判断截断出来的是否是“sentence”。比如“B”和"ByI BMyQ"前半段也相等,但截出来的不是句子。加在中间的需要前后各判断一遍,前面指针i2一直走到不相等的位置,后面ii2往前走到不相等的位置,如果ii2 < i2则证明中间可以加一个句子使给定的一个句子变成另外一个,否则不可以
代码:
class Solution {
public:
bool areSimilar(string& s1, string& s2){
int l1 = s1.length(), l2 = s2.length();
if((s1.substr(0, l2) == s2 && s1[l2] == ' ') ||
(s1.substr(l1-l2, l2) == s2 && s1[l1-l2-1] == ' ')) return true;
int i1 = 0, i2 = 0;
while(i2 < s2.length()){
int j1 = s1.find(' ', i1), j2 = s2.find(' ', i2);
if(s1.substr(i1, j1-i1) == s2.substr(i2, j2-i2)){
i1 = j1+1;
i2 = j2+1;
} else break;
}
int ii1 = s1.length()-1, ii2 = s2.length()-1;
while(ii2 >= 0){
int j1 = s1.rfind(' ', ii1), j2 = s2.rfind(' ', ii2);
if(s1.substr(j1+1, ii1-j1) == s2.substr(j2+1, ii2-j2)){
ii1 = j1-1;
ii2 = j2-1;
} else break;
}
return ii2 < i2;
}
bool areSentencesSimilar(string sentence1, string sentence2) {
if(sentence1.length() == sentence2.length()) return sentence1 == sentence2;
if(sentence1.length() > sentence2.length()) return areSimilar(sentence1, sentence2);
return areSimilar(sentence2, sentence1);
}
};
time:(O(M+N)). space:O(1)