#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef long double ld;
#define rep(i,n) for(ll i=0;i<(n);i++)
#define init(a,i) for(int k=0;k<(i);k++)(a)[k]=0
#define in(a,i) for(int k=0;k<(i);k++)cin>>(a)[k]
#define all(a)  (a).begin(),(a).end()
#define mod 998244353
#define inf 2147483647
#define range(x,a,b) (a)<=x&&x<=(b)
int main(){
	int n;
	string s;
	cin>>n>>s;
	int pair1=0,pair2=0,count=0;
	rep(i,n){
		pair1=0;
		pair2=0;
		for(int j=i;j<n;j++){
			switch(s[j]){
				case 'A':
				pair1++;
				break;
				case 'T':
				pair1--;
				break;
				case 'C':
				pair2++;
				break;
				case 'G':
				pair2--;
				break;
			}
			if(pair1==0&&pair2==0)count++;
		}
	}
	cout<<count;
	return 0;
}
#include<bits/stdc++.h>
#define pb emplace_back
#define AI(i) begin(i), end(i)
using namespace std;
using ll = long long;
template<class T>
bool chmax(T &val, T nv) { return val < nv ? (val = nv, true) : false; }
template<class T>
bool chmin(T &val, T nv) { return nv < val ? (val = nv, true) : false; }
#ifdef KEV
#define DE(args...) kout("[ " + string(#args) + " ] = ", args)
void kout() {cerr << endl;}
template<class T1, class ...T2>
void kout (T1 v, T2 ...e) { cerr << v << ' ', kout(e...); }
template<class T>
void debug(T L, T R) { while (L != R) cerr << *L << " \n"[next(L)==R], ++L; }
#else
#define DE(...) 0
#define debug(...) 0
#endif
const int MAX_N = 2010;
char w[MAX_N][MAX_N];
bool used[MAX_N];
int dis[MAX_N][MAX_N];
int n, m;
vector<pair<int,int>> ap[ MAX_N ];
int solve() {
	memset(dis, -1, sizeof(dis));
	queue<pair<int,int>> q;
	int x, y;
	for (int i = 1;i <= n;++i)
		for (int j = 1;j <= m;++j) {
			if (w[i][j] == 'S')
				q.emplace(i, j), x = i, y = j;
			if (w[i][j] <= 'z' && w[i][j] >= 'a')
				ap[ w[i][j] ].pb(i, j);
		}
	dis[x][y] = 0;
	while (q.size()) {
		auto [x, y] = q.front(); q.pop();
		//DE(x, y, dis[x][y]);
		int d = dis[x][y] + 1;
		auto update = [&](int x, int y) {
			if (x < 1 || y < 1 || x > n || y > m || dis[x][y] != -1 || w[x][y] == '#') return;
			dis[x][y] = d;
			q.emplace(x, y);
		};
		update(x+1, y), update(x-1, y), update(x, y-1), update(x, y+1);
		if (w[x][y] <= 'z' && w[x][y] >= 'a' && !used[ w[x][y] ]) {
			used[ w[x][y] ] = true;
			for (auto [a, b] : ap[w[x][y]])
				update(a, b);
		}
	}
	for (int i = 1;i <= n;++i)
		for (int j = 1;j <= m;++j)
			if (w[i][j] == 'G')
				return dis[i][j];
	assert(false);
}
int32_t main() {
	ios_base::sync_with_stdio(0), cin.tie(0);
	cin >> n >> m;
	for (int i = 1;i <= n;++i)
		cin >> w[i] + 1;
	cout << solve() << '\n';
}

