Make string S equal to T after replacing some prefix characters in S


#include <bits/stdc++.h>

using namespace std;

  

int solve(string s, string t)

{

    int n = s.size();

    string ss = s, tt = t;

    sort(ss.begin(), ss.end()), sort(tt.begin(), tt.end());

  

    

    if (ss != tt) {

        return -1;

    }

    int ans = n;

    int left = 0, right = n - 1;

    reverse(t.begin(), t.end());

    while (left < right) {

  

        

        int mid = (left + right) / 2;

        int cur = n - 1;

        for (auto ch : t) {

            if (cur == mid - 1)

                break;

  

            

            

            if (ch == s[cur]) {

                --cur;

            }

        }

  

        if (cur == mid - 1) {

            right = mid;

            ans = right;

        }

        else {

            left = mid + 1;

        }

    }

    return ans;

}

  

int main()

{

    string s = "abab";

    string t = "abba";

  

    

    cout << solve(s, t);

    return 0;

}


#include <bits/stdc++.h>

using namespace std;

  

int solve(string s, string t)

{

    int n = s.size();

    string ss = s, tt = t;

    sort(ss.begin(), ss.end()), sort(tt.begin(), tt.end());

  

    

    if (ss != tt) {

        return -1;

    }

    int ans = n;

    int left = 0, right = n - 1;

    reverse(t.begin(), t.end());

    while (left < right) {

  

        

        int mid = (left + right) / 2;

        int cur = n - 1;

        for (auto ch : t) {

            if (cur == mid - 1)

                break;

  

            

            

            if (ch == s[cur]) {

                --cur;

            }

        }

  

        if (cur == mid - 1) {

            right = mid;

            ans = right;

        }

        else {

            left = mid + 1;

        }

    }

    return ans;

}

  

int main()

{

    string s = "abab";

    string t = "abba";

  

    

    cout << solve(s, t);

    return 0;

}

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! Techno Blender is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – admin@technoblender.com. The content will be deleted within 24 hours.
CharactersEqualLatestPrefixReplacingstringTechTechnology
Comments (0)
Add Comment