📌  相关文章
📜  检查是否可以通过插入最多 1 个字符串来使给定的字符串相等

📅  最后修改于: 2022-05-13 01:56:10.706000             🧑  作者: Mango

检查是否可以通过插入最多 1 个字符串来使给定的字符串相等

给定两个句子S1S2 ,任务是通过在两个句子中的任何一个中插入最多一个句子(可能是空的)来检查句子是否相等。

例子:

方法:以下观察有助于解决问题:

  • 如果两个句子的大小相等,但它们本身并不相同,则它们不能相等。
  • 去掉两个句子的最长公共前缀和最长公共后缀后,如果至少有一个为空,则表示可以相等。

这个问题可以在双端队列的帮助下解决。请按照以下步骤解决问题:

  • 检查S1S2的大小是否相等。如果它们相等,请执行以下操作:
    • 如果S1等于S2 ,则返回true
    • 否则,返回false
  • 初始化两个双端队列XY
  • S1的所有单词推入X
  • S2的所有单词推入Y
  • 虽然XY的正面相同,但从XY的正面弹出。
  • 虽然XY的背面相同,但从XY的背面弹出。
  • 检查XY中的任何一个是否为空。如果其中任何一个为空,则返回true
  • 否则,返回false

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to check whether
// two sentences can be made equal
// by inserting at most
// one sentence in one of them
bool areSimilar(string S1, string S2)
{
    // size of sentence S1
    int N = S1.size();
 
    // size of sentence S2
    int M = S2.size();
 
    // check if S1 and S2
    // are of equal sizes
    if (N == M) {
        // if both sentences are
        // the same, return true
        if (S1 == S2)
            return true;
 
        // Otherwise, return false
        return false;
    }
 
    // Declare 2 deques X and Y
    deque X, Y;
 
    // insert ' ' at the end of both
    // sentences so that the last
    // word can be identified
    S1.push_back(' ');
    S2.push_back(' ');
 
    string temp = "";
 
    // traverse the sentence S1
    for (int i = 0; i < N + 1; i++) {
 
        // push temp in deque
        // when a space comes in sentence
        // i.e a word has been formed
        if (S1[i] == ' ') {
            X.push_back(temp);
            temp = "";
        }
        else {
            // temp stores words
            // of the sentence
            temp += S1[i];
        }
    }
 
    // traverse the sentence S1
    for (int i = 0; i < M + 1; i++) {
 
        // push temp in deque
        // when a space comes in sentence
        // i.e a word has been formed
        if (S2[i] == ' ') {
            Y.push_back(temp);
            temp = "";
        }
        else {
            // temp stores words of the sentence
            temp += S2[i];
        }
    }
 
    // check for prefixes of both sentences
    while (X.size() > 0 && Y.size() > 0
           && X.front() == Y.front()) {
 
        // pop the prefix from both
        // deques till they are equal
        X.pop_front();
        Y.pop_front();
    }
 
    // check for suffixes of both sentences
    while (X.size() > 0 && Y.size() > 0
           && X.back() == Y.back()) {
 
        // pop the suffix from both deques
        // till they are equal
        X.pop_back();
        Y.pop_back();
    }
 
    // if any of the deques is empty
    // return true
    if (X.size() == 0 || Y.size() == 0)
        return true;
 
    // if both the deques are
    // not empty return false
    return false;
}
// Driver code
int main()
{
    // Input
    string S1 = "Start practicing on GeeksforGeeks";
    string S2 = "Start GeeksforGeeks";
 
    // function call
    if (areSimilar(S1, S2))
        cout << "True" << endl;
    else
        cout << "False" << endl;
    return 0;
}


Python3
# Python3 program for the above approach
from collections import deque
 
# Function to check whether
# two sentences can be made equal
# by inserting at most
# one sentence in one of them
def areSimilar(S1, S2):
     
    S1 = [i for i in S1]
    S2 = [i for i in S2]
     
    # Size of sentence S1
    N = len(S1)
 
    # Size of sentence S2
    M = len(S2)
 
    # Check if S1 and S2
    # are of equal sizes
    if (N == M):
         
        # If both sentences are
        # the same, return True
        if (S1 == S2):
            return True
 
        # Otherwise, return false
        return False
 
    # Declare 2 deques X and Y
    X, Y = deque(), deque()
 
    # Insert ' ' at the end of both
    # sentences so that the last
    # word can be identified
    S1.append(' ')
    S2.append(' ')
 
    temp = ""
 
    # Traverse the sentence S1
    for i in range(N + 1):
         
        # Push temp in deque
        # when a space comes in sentence
        # i.e a word has been formed
        if (S1[i] == ' '):
            X.append(temp)
            temp = ""
        else:
             
            # temp stores words
            # of the sentence
            temp += S1[i]
 
    # Traverse the sentence S1
    for i in range(M + 1):
         
        # Push temp in deque
        # when a space comes in sentence
        # i.e a word has been formed
        if (S2[i] == ' '):
            Y.append(temp)
            temp = ""
        else:
             
            # temp stores words of the sentence
            temp += S2[i]
 
    # Check for prefixes of both sentences
    while (len(X) > 0 and
           len(Y) > 0 and X[0] == Y[0]):
 
        # Pop the prefix from both
        # deques till they are equal
        X.popleft()
        Y.popleft()
 
    # Check for suffixes of both sentences
    while (len(X) > 0 and len(Y) > 0 and
           X[-1] == Y[-1]):
                
        # Pop the suffix from both deques
        # till they are equal
        X.pop()
        Y.pop()
 
    # If any of the deques is empty
    # return True
    if (len(X) == 0 or len(Y) == 0):
        return True
 
    # If both the deques are
    # not empty return false
    return False
 
# Driver code
if __name__ == '__main__':
     
    # Input
    S1 = "Start practicing on GeeksforGeeks"
    S2 = "Start GeeksforGeeks"
 
    # Function call
    if (areSimilar(S1, S2)):
        print("True")
    else:
        print("False")
 
# This code is contributed by mohit kumar 29


输出
True

时间复杂度: O(N+M),其中 N 和 M 分别是 S1 和 S2 的大小。
辅助空间: O(N+M)