626A.Robot Sequence

本文探讨了一个位于无限矩形网格中的机器人如何通过执行其源代码中的连续子串指令返回起点的问题。具体而言,机器人遵循一系列向上(U)、向下(D)、向左(L)和向右(R)的指令。文章提供了一段Python代码示例,该代码能够计算出所有能让机器人回到起点的有效子串数量。
A. Robot Sequence
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices.

Input

The first line of the input contains a single positive integer, n (1 ≤ n ≤ 200) — the number of commands.

The next line contains n characters, each either 'U', 'R', 'D', or 'L' — Calvin's source code.

Output

Print a single integer — the number of contiguous substrings that Calvin can execute and return to his starting square.

Examples
input
6
URLLDR
output
2
input
4
DLUU
output
0
input
7
RLRLRLR
output
12
Note

In the first case, the entire source code works, as well as the "RL" substring in the second and third characters.

Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result.

思路:求字符串中能使其回到原点的子串,包括其自身,利用暴力求解
[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #!/usr/bin/python  
  2. # -*-coding:utf-8 -*-  
  3. from collections import Counter  
  4. n=int(raw_input())  
  5. commands=list(raw_input())  
  6. ans=0  
  7. for i in range(n):  
  8.     for j in range(i+1,n+1):  
  9.         c=Counter(commands[i:j])  
  10.         if c['R']==c['L'and c['U']==c['D']:  
  11.             ans+=1  
  12. print ans  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值