一、题目
二、思路(自己)
- 值得注意的是,题目给出了一个条件不能从字符串两端删除颜色片段。从示例可以理解的是,跳过首个字符和末个字符,从中间开始进行计算。
- 按照一般的方法的话就是:搜索相同的连续字符串,然后计算A和B连续字符串的个数和。比较大小即可。
- 发现理解错题意了,不饿能删除字符串两端的颜色是指要三个相同的连续然后删除中间的。
class Solution {
public boolean winnerOfGame(String colors) {
int anum=0,bnum=0;
if(colors.length()<=2) return false;
String s=colors.substring(1,colors.length()-1);
char[] c=s.toCharArray();
for (int i = 0; i < c.length-1; i++) {
if(c[i]==c[i+1]){
if(c[i]=='A') anum++;
else bnum++;
}
}
if(anum>bnum) return true;
else return false;
}
}
- 怪不得这个示例出错了。修改代码后为
class Solution {
public boolean winnerOfGame(String colors) {
int anum=0,bnum=0;
if(colors.length()<=2) return false;
char[] c=colors.toCharArray();
for (int i = 1; i < c.length-1; i++) {
if(c[i]==c[i-1]&&c[i]==c[i+1]){
if(c[i]=='A') anum++;
else bnum++;
}
}
return anum-bnum>0;
}
}
- 这个题目太简单了,比很多简单题都要简单很多!不知道官方为什么要给他定义为中等题
三、题解(官方)
官方答案思路差不多,感觉写的比我大还复杂一些,我就不贴了。加油加油!!!(ง •_•)ง
PS:不过我刚才看见评论区有一个挺好的代码,也听整洁的,贴上:
class Solution {
public boolean winnerOfGame(String colors) {
int count = 0;
for(int i = 0; i < colors.length()-2; i++){
if(colors.substring(i,i+3).equals("AAA")) count++;
if(colors.substring(i,i+3).equals("BBB")) count--;
}
return count > 0;
}
}