Command Sequence
Problem Description
There is a robot that can move by receiving a sequence of commands.
There are four types of command in the command sequence:
U: robot moves one unit up.
D: robot moves one unit down.
L: robot moves one unit left.
R: robot moves one unit right.
Now, given a command sequence of length n. You need to find out how
many substrings of the command sequence satisfy that if the robot
execute the substring command, it can return to the starting position.A substring is a contiguous sequence of characters within a string.
For instance, “the best of” is a substring of “It was the best of
times”. For example, “Itwastimes” is a subsequence of “It was the best
of times”, but not a substring.
Input
This problem contains multiple test cases.
The first line contains an integer t (1≤t≤20) indicating the number of
test cases.For each test case, the first line contains one integer n (2≤n≤105).
The second line contains a UDLR string of length n.
Output
For each test case, output one line one integer indicating the answer.
Sample Input
1
6
URLLDR
Sample Output
2
AC代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
map<pair<int,int>,int> mp;
int n , m;
int main()
{
int n , t;
char s[100005];
cin >> t;
while(t--)
{
cin >> n >> s;
int x=0 , y=0 ;
mp.clear();
mp[{0,0}]=1;
int sum=0;
for(int i = 0 ; i < n ; i++)
{
if(s[i]=='L')
x--;
else if(s[i]=='R')
x++;
else if(s[i]=='U')
y++;
else
y--;
if(mp[{x,y}]>0)
{
sum=sum+mp[{x,y}];
}
mp[{x,y}]++;
}cout<<sum<<endl;
}
return 0;
}