概述
import java.util.*;
public class StonesOnTheTable {
public static void main(String[] args) {
Scanner inScanner = new Scanner(System.in);
int n = inScanner.nextInt();
String tempString = inScanner.next();
List list = new ArrayList();
char[] x = tempString.toCharArray();
for (int i = 0; i < n; i++) {
list.add(x[i]);
}
// preparing work for transform String to List//remember that when
// remove the element in the list, the set that deleted will be filled
// automatically
int temp = 0, count = 0;// ini
for (int i = 0; i < list.size() - 1; i++) {
temp = i + 1;// update//ini
while (temp < list.size()) {
if (list.get(i).equals(list.get(temp))) {
list.remove(temp);
count++;
} else
break;
}
}
System.out.println(count);
}
}
最初的思路在于依次判断小球右侧球颜色是否相同,若相同则删除,然后判断下个相邻球是否仍旧同色,若同色则继续删除,若不同色则跳到下个小球进行判断,依次同理。需要注意的是List数据结构在小球被删除后,索引之后的小球会自动将被删小球的位置填充,所以temp不需要进行人为增加。当发现相邻小球颜色不一的时候,就立刻跳出循环。
但写完后发现思考不周全,方法繁琐。题目只要求输出最小次数,并无要求得出最后符合要求的颜色序列,只要将题意简化为依次计算每个小球右侧颜色一样的小球即可。
import java.util.*;
public class Stones {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int n = kbd.nextInt();
String s = kbd.next();
int r = 0;
for(int i = 1;i<s.length();i++) {
if(s.charAt(i-1)==s.charAt(i)) {
r++;
}
}
System.out.println(r);
}
}
最后
以上就是俭朴石头为你收集整理的CodeForces-266A-Stones on the Table的全部内容,希望文章能够帮你解决CodeForces-266A-Stones on the Table所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复