首先,字符串的长度len肯定为偶数,否则不可能同时形成配对的U - D 和 R - L
设字符串中U,D,R,L的数量分别为cu,cd,cr,cl
t1 = cu + cd t2 = cr + cl
在len为偶数的情况下,有两种情况:
1. t1和t2同时为奇
2. t1和t2同时为偶
同时为奇数的时候,则cu和cd尽可能平摊,多的一个给cr和cl,然后cr和cl再平摊,平摊的过程中记录变换的个数
同时为偶数的时候cu和cd直接平摊,cr和cl直接平摊就可以了,同样过程中记录变换的个数
#include <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
#include <map>
using namespace std;
const int maxn = 100000;
char s[maxn + 5];
int len;
int main()
{
int cu, cd, cr, cl, ans, t1, t2;
scanf("%s", s);
len = strlen(s);
if (len % 2) {
cout << -1 << endl;
return 0;
}
map<char, int> m;
for (int i = 0; i < len; i++) {
m[s[i]]++;
}
cu = m['U'];
cd = m['D'];
t1 = cu + cd;
cr = m['R'];
cl = m['L'];
t2 = cr + cl;
if (t1 % 2 && t2 % 2) {
ans = max(cu, cd) - t1 / 2;
ans = ans + max(cl, cr) - (t2 + 1) / 2;
} else if(t1 % 2 == 0 && t2 % 2 == 0) {
ans = max(cu, cd) - t1 /2 + max(cl, cr) - t2 / 2;
}
cout << ans << endl;
return 0;
}