#include <cstdio>
#include <cstring>
#include <vector>
#include <deque>
#define MAXN 1000010
using namespace std;

int n;
char s1[MAXN],s2[MAXN];
vector<int> S[30];
int p[MAXN];

struct Queue{
	deque<int> Q;
	int d;

	void push_back(int x){ Q.push_back(x-d); }
	void push_front(int x){ Q.push_front(x-d); }
	int back(){ return Q.back()+d; }
	void pop_back(){ Q.pop_back(); }
	void pop_front(){ Q.pop_front(); }
	bool empty(){ return Q.empty(); }
	int size(){ return Q.size(); }
}Q;

int main(){
#ifdef DEBUG
	freopen("F.in","r",stdin);
#endif
	scanf("%d",&n);
	scanf("%s%s",s1+1,s2+1);
	n=strlen(s1+1);
	for(int i=1;i<=n;i++) S[s1[i]-'a'].push_back(i);
	int ans=0;
	p[n+1]=n+1;
	for(int i=n;i>=1;i--){
		if(s2[i]==s2[i+1] && i>=p[i+1]){
			p[i]=p[i+1];
		}else{
			while(!S[s2[i]-'a'].empty() && S[s2[i]-'a'].back()>=p[i+1])
				S[s2[i]-'a'].pop_back();
			if(S[s2[i]-'a'].empty()){
				puts("-1");
				return 0;
			}
			p[i]=S[s2[i]-'a'].back();
			if(i>=p[i+1]){
				Q.d--;
				Q.push_front(p[i+1]-1);
				while(Q.back()>=i) Q.pop_back();
				Q.push_back(i);
			}else{
				while(!Q.empty()) Q.pop_back();
				if(p[i]<i) Q.push_back(i);
			}
			ans=max(ans,(int)Q.size());
		}
	}
	printf("%d\n",ans);
}

#include <cstdio>
#include <algorithm>

#define rep(i, n) for(int i = 0; i < (n); ++i)

using namespace std;

typedef pair<int, int> P;
typedef pair<int, P> Q;

int n, m;
Q g[100000];
int p[10000];
int r[10000];

void init(){
	rep(i, n){
		p[i] = i;
		r[i] = 0;
	}
}

int find(int i){
	return p[i] == i ? i : p[i] = find(p[i]);
}

bool same(int i, int j){
	return find(i) == find(j);
}

void unite(int i, int j){
	int a = find(i);
	int b = find(j);

	if(a == b){
		return;
	}

	if(r[a] > r[b]){
		p[b] = a;
	}
	else{
		p[a] = b;
		if(r[a] == r[b]){
			++r[b];
		}
	}
}

int main(){
	scanf("%d%d", &n, &m);
	rep(i, m){
		int a, b, c;
		scanf("%d%d%d", &a, &b, &c);
		g[i] = Q(c, P(a, b));
	}

	sort(g, g + m);
	
	init();

	int ans = 0;
	rep(i, m){
		int a = g[i].second.first;
		int b = g[i].second.second;
		int c = g[i].first;

		if(!same(a, b)){
			unite(a, b);
			ans += c;
		}
	}
	printf("%d\n", ans);
	return 0;
}