首页 > 编程语言 > 详细

算法题

时间:2020-05-12 16:50:02      阅读:56      评论:0      收藏:0      [点我收藏+]

有个机器人在数轴上走路,起始位置在原点,每走一步就是一个数。只能左右走,往左是L,往右是R,路径中只包含‘R’和‘L’,路径可以重复走,每走一步可以获得对应数的糖果,但是重复走没有糖果。输入值分为三个:第一行两个数字,空格隔开,分别为:走的步数,以及重复的次数。第二行是走的路径。
举例:
3 2
RRR
说明机器人执行路径RRR两次。即:RRRRRR
计算过程:
1+2+3+4+5+6=21

 

 

 

public static void main(String[] args) {
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
Scanner input1 = new Scanner(System.in);
System.out.println("走的步数,以及重复的次数:");
String s1 = input1.nextLine();
Scanner input2 = new Scanner(System.in);
System.out.println("请输入路径:");
String s2 = input2.nextLine().toUpperCase();
String root="";
String a[]=s1.split(" ");
for(int i=0;i<Integer.valueOf(a[1]);i++){
root+=s2;
}
Integer sum=0;
Integer tmp=0;
String b[]=root.split("");
for(int i=1;i<b.length;i++){
String direct=b[i];
if(i==1){
if("R".equals(direct)){
tmp=1;
map.put(tmp, 1);
}else{
tmp=-1;
map.put(tmp, -1);
}
}else{
if("R".equals(direct)){
tmp=tmp+1;
}else{
tmp=tmp-1;
}
if(!map.containsKey(String.valueOf(tmp))){
map.put(tmp, tmp);
}
}
}
for(Map.Entry<Integer, Integer> entry : map.entrySet()){
sum+=Math.abs(entry.getValue());
}
System.out.println("总糖水果数为:"+sum);
}

算法题

原文:https://www.cnblogs.com/foreverstudy/p/12877042.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!