首页 > 其他分享 >1813. Sentence Similarity III

1813. Sentence Similarity III

时间:2023-01-16 17:34:25浏览次数:36  
标签:return name Sentence sentence Similarity sentence1 sentence2 sentences 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.

 

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.

双指针

若要符合定义,短的字符串一定出现在长的字符串的两端。

class Solution {
public:
    bool areSentencesSimilar(string sentence1, string sentence2) {
        vector<string>sen1;
        vector<string>sen2;
        string word="";
        for(auto ch:sentence1){
            if(ch>='A'&&ch<='z')    word+=ch;
            else    sen1.push_back(word),word="";
        }
        sen1.push_back(word),word="";
        for(auto ch:sentence2){
            if(ch>='A'&&ch<='z')    word+=ch;
            else    sen2.push_back(word),word="";
        }
        sen2.push_back(word);
        if(sen1.size()<sen2.size())     swap(sen1,sen2);
        int i=0,j=0;
        while(i<sen2.size()&&sen1[i]==sen2[i])  i++;
        while(j<sen2.size()&&sen1[sen1.size()-1-j]==sen2[sen2.size()-1-j])  j++;
        if(i+j>=sen2.size())
            return true;
        return false;
    }
};

标签:return,name,Sentence,sentence,Similarity,sentence1,sentence2,sentences,III
From: https://www.cnblogs.com/SkyDusty/p/17055957.html

相关文章