牛牛喜欢彩色的东西,尤其是彩色的瓷砖。牛牛的房间内铺有L块正方形瓷砖。每块砖的颜色有四种可能:红、绿、蓝、黄。给定一个字符串S, 如果S的第i个字符是'R', 'G', 'B'或'Y',那么第i块瓷砖的颜色就分别是红、绿、蓝或者黄。
牛牛决定换掉一些瓷砖的颜色,使得相邻两块瓷砖的颜色均不相同。请帮牛牛计算他最少需要换掉的瓷砖数量。
输入包括一行,一个字符串S,字符串长度length(1 ≤ length ≤ 10),字符串中每个字符串都是'R', 'G', 'B'或者'Y'。
输出一个整数,表示牛牛最少需要换掉的瓷砖数量
RRRRRR
3
import java.util.Scanner; public class Test1{ public static void main(String[]args){ Scanner sc=new Scanner(System.in); String str=sc.next(); int count=0; for(int i=0;i<str.length();i++){ char c=str.charAt(i); if(str.charAt(i)==str.charAt(i+1)){ count++; i++; } } System.out.println(count); } }
}
import java.util.Scanner; /* 两两判断,碰到相同的直接替换就可以,因为有四块砖,保证替换的那块跟它的前面和后面都不相同就可以,所以 一定可以找到一个与前面不同同时与后面不同的替换,因此可以直接替换。 对字符串进行两两判断,找到相邻两个相同的,就将计数器加一,然后直接跳过这两个,从下一个开始判断,就是两两判断 */ public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()){ String str = sc.next(); System.out.println(replaceBrick(str)); } } private static int replaceBrick(String str) { int len = str.length(); int count = 0; char[] cStr = str.toCharArray(); for (int i = 1; i < len; i++) { if(cStr[i]==cStr[i-1]){ count++; i++; } } return count; } }
import java.util.Scanner; public class ColorTile { public static int Change(String s) { if (s.length() == 1) { return 0; } int count = 1; int num = 0; // 所有相同字符的子串长度/2相加就是最少需要换掉的瓷砖数量, // RRR只需换掉1块,RRRR需要换掉2块,RRRRRR需要换掉3块,即相同字符的子串长度/2 // 如RRRGGGBBYYY,3/2+3/2+2/2+3/2=4 for (int i = s.length() - 1; i > 0; i--) { if (s.charAt(i) == s.charAt(i - 1)) count++; else { if (count > 1) { num += count / 2; count = 1; } } } if (count > 1) num += count / 2; return num; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String s = sc.nextLine(); System.out.println(Change(s)); } } }