String Manipulation - Alternating Characters [Easy]
交替字符
hashank非常喜欢字符串,特别是那些连续字符都是不一样的字符串。比如:他喜欢,但他不喜欢。给定一个字符串,该字符串只可能由字母和组成。Shashank想把这个字符串转变成他喜欢的字符串,在转变的过程中,他允许删除字符串中的某些字符。 你的任务就是找出最少需要删除几个字符,才能把给定的字符串转变成Shashank喜欢的字符串。
样例输入:
5
AAAA
BBBBB
ABABABAB
BABABA
AAABBB
样例输出:
3
4
0
0
4
样例解释:
, 需要删除3个字符
, 需要删除4个字符
, 需要删除0个字符
, 需要删除0个字符
, 需要删除4个字符
static int alternatingCharacters(String s) {
int deletions = 0;
int currentCount = 1;
for(int i = 1; i < s.length(); i++)
{
if(s.charAt(i) != s.charAt(i-1))
{
deletions += currentCount - 1;
currentCount = 1;
continue;
}
currentCount++;
}
deletions += currentCount - 1;
return deletions;
}
留言
張貼留言