Compilation of procedure C+++



  • There's a task I just don't understand, that's how it sounds:

    введите сюда описание изображения

    I tried to write something, but I don't think it's the way it is, can you help me?

    #include <iostream>
    using namespace std;
    

    void line_delete(string& line1, string& line2)
    {
    for (int i = 0; i < line1.length(); i++)
    {

        for (int j = 0; j &lt; line2.length(); j++)
        {
            if (line1[i] == line2[j])
            {
                line1.erase(i, 1);
                j = 0;
                i -= 1;
            }
        }
    }
    

    }
    int main()
    {
    string line1;
    string line2;
    cin >> line1;
    cin >> line2;

    cout &lt;&lt; line1 &lt;&lt; endl;
    line_delete(line1, line2);
    cout &lt;&lt; line2 &lt;&lt; endl;
    

    }



  • Actually, it's not very good to remove the elements of the line in the cycle on this line, it's almost always a mistake or something that's not good.

    The following can be done:

    Put a new line on it with one symbol that is missing in the second line.

    In your example, the internal cycle will only be needed to determine whether the symbol is in the second line or not.

    Although this does not require a cycle, a method can be used find - the symbol or will be found in line 2 or not.

    Then, of course, making the task O(n^2) difficult, too, it's not good, it's me for two cycles alone.

    First, you can optimize as I wrote above - through the method. find

    Second, the second line can be converted into multiple lines.std::set) and then searching for symbols is at least O(log(n) time, which is the total complexity of O(n*log(n))

    Option 1:

    void line_delete(std::string& line1, const std::string& line2)
    {
        std::string res = "";
    
    for (const char letter : line1)
    {
        if (line2.find(letter) == -1)
            res.push_back(letter);
    }
    
    line1 = res;
    

    }

    Option 2:

    void line_delete(std::string& line1, const std::string& line2)
    {
    std::string res = "";

    std::set&lt;char&gt; dict;
    
    for (const char letter : line2)
    {
        dict.insert(letter);
    }
    
    for (const char letter : line1)
    {
        if (dict.find(letter) == dict.end())
            res.push_back(letter);
    }
    
    line1 = res;
    

    }



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2