762C - Two strings - CodeForces Solution


binary search hashing strings two pointers *2100

Please click on ads to support us..

Python Code:

import sys
 
input = sys.stdin.readline
 
def solve():
	a = input().strip()
	b = input().strip()
 
	n = len(a)
	m = len(b)
	c = [0]*m
	d = [0]*m
 
	p = 0
	for i in range(m):
		for j in range(p, n):
			if a[j] == b[i]:
				c[i] = j
				p = j + 1
				break
		else:
			for j in range(i,m):
				c[j] = n
			break
	p = n-1
	for i in range(m-1,-1,-1):
		for j in range(p,-1,-1):
			if a[j] == b[i]:
				d[i] = j
				p = j - 1
				break
		else:
			for j in range(i,-1,-1):
				d[j] = -1
			break
	j = 0
	while j < m and d[j] < 0:
		j += 1
	res = (m-j, 0, j)
	for i in range(m):
		p = c[i]
		if p == n:
			break
		while j < m and (j <= i or d[j] <= p):
			j += 1
		res = max(res,(i+1+m-j,i+1,j))
	if res[0] == 0:
		print('-')
	else:
		print(b[:res[1]]+b[res[2]:])
 
solve()

C++ Code:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N = 1e5 + 10;
ll pre[N], suf[N];
char s[N], t[N];
int main() {
    scanf("%s%s", s + 1, t + 1);
    ll n1 = strlen(s + 1), n2 = strlen(t + 1), last = 0;
    for (ll i = 1; i <= n1; i++) {
        pre[i] = n2, suf[i] = 1;
    }
    suf[n1 + 1] = n2 + 1;
    for (ll i = 1, j = 1; i <= n1 && j <= n2; i++) {
        if (s[i] == t[j]) {
            last = j;
            j++ ;
        }
        pre[i] = last;
    }
    last = n2 + 1;
    for (ll i = n1, j = n2; i >= 1 && j >= 1; i--) {
        if (s[i] == t[j]) {
            last = j;
            j--;
        }
        suf[i] = last;
    }
    // for (ll i = 1; i <= n1; i++) {
    //     cout << pre[i] << ' ' << suf[i] << endl;
    // }
    ll res = n2 + 1, l, r;
    for (ll i = 1; i <= n1 + 1; i++) {
        if (pre[i - 1] < suf[i]) {
            if (res > suf[i] - pre[i - 1]) {
                res = suf[i] - pre[i - 1];
                l = pre[i - 1];
                r = suf[i];
            }
        }
    }
    if (res == n2 + 1) {
        puts("-");
    } else {
        for (int i = 1; i <= n2; i++) {
            if (i <= l || i >= r) {
                cout << t[i];
            }
        }
        puts("");
    }
}


Comments

Submit
0 Comments
More Questions

1480A - Yet Another String Game
1216C - White Sheet
1648A - Weird Sum
427A - Police Recruits
535A - Tavas and Nafas
581A - Vasya the Hipster
1537B - Bad Boy
1406B - Maximum Product
507B - Amr and Pins
379A - New Year Candles
1154A - Restoring Three Numbers
750A - New Year and Hurry
705A - Hulk
492B - Vanya and Lanterns
1374C - Move Brackets
1476A - K-divisible Sum
1333A - Little Artem
432D - Prefixes and Suffixes
486A - Calculating Function
1373B - 01 Game
1187A - Stickers and Toys
313B - Ilya and Queries
579A - Raising Bacteria
723A - The New Year Meeting Friends
302A - Eugeny and Array
1638B - Odd Swap Sort
1370C - Number Game
1206B - Make Product Equal One
131A - cAPS lOCK
1635A - Min Or Sum