HackerRank Alternating Characters Solution
In this post, we will solve HackerRank Alternating Characters Problem Solution.
You are given a string containing characters A and B only. Your task is to change it into a string such that there are no matching adjacent characters. To do this, you are allowed to
delete zero or more characters in the string.
Your task is to find the minimum number of required deletions.
Example
8 = AABAAB
Remove an A at positions 0 and 3 to make s = ABAB in 2 deletions.
Function Description
Complete the alternatingCharacters function in the editor below.
alternatingCharacters has the following parameter(s):
- string s: a string
Returns
- int: the minimum number of deletions required
Input Format
The first line contains an integer q, the number of queries.
The next q lines each contain a string s to analyze.
Sample Input
5
AAAA
BBBBB
ABABABAB
BABABA
AAABBB
Sample Output
3
4
0
0
4
Explanation
The characters marked red are the ones that can be deleted so that the string does not have matching adjacent characters.
Alternating Characters C Solution
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_DISABLE_PERFCRIT_LOCKS
#define getchar_unlocked() getchar()
#define putchar_unlocked(c) putchar(c)
#endif
#include <stdio.h>
#include <stdlib.h>
#define mygc(c) (c)=getchar_unlocked()
#define mypc(c) putchar_unlocked(c)
void reader(int *x){ int k, m = 0; *x = 0; for (;;){ mygc(k); if (k == '-'){ m = 1; break; }if ('0' <= k&&k <= '9'){ *x = k - '0'; break; } }for (;;){ mygc(k); if (k<'0' || k>'9')break; *x = (*x) * 10 + k - '0'; }if (m)(*x) = -(*x); }
void readln(char *x){ int i = 1, k; for (;;){ mygc(k); if ('-' <= k&&k <= 'z'){ x[0] = k; break; } }for (;;){ mygc(k); if (k<'-' || k>'z') { x[i] = 0; break; } x[i] = k, i++; } }
void writer(int x, char c){ int sz = 0, m = 0; char buf[10]; if (x<0)m = 1, x = -x; while (x)buf[sz++] = x % 10, x /= 10; if (!sz)buf[sz++] = 0; if (m)mypc('-'); while (sz--)mypc(buf[sz] + '0'); mypc(c); }
int main() {
int T, ans;
char cur, pre;
char buf[100002];
reader(&T);
for (int i = 0; i < T; i++) {
ans = 0, cur = -1;
readln(buf);
int j = 0;
while (buf[j]) {
pre = cur;
cur = buf[j];
if (cur == pre) { ans++; }
j++;
}
writer(ans, '\n');
}
getchar();
return 0;
}
Alternating Characters C++ Solution
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
std::string input;
std::getline(std::cin, input);
int tests = std::stoi(input);
for (int i = 0; i < tests; i++) {
std::string s;
std::getline(std::cin, s);
int deletions = 0;
char current = 0;
for (auto c: s) {
if (c == current) {
deletions++;
} else {
current = c;
}
}
std::cout << deletions << std::endl;
}
return 0;
}
Alternating Characters C Sharp Solution
using System;
using System.Collections.Generic;
using System.IO;
class Solution {
static void Main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
int count = Convert.ToInt32(Console.ReadLine());
string[] strings = new string[count];
for (int i = 0; i < count; i++)
{
strings[i] = Console.ReadLine();
}
for (int i = 0; i < count; i++)
{
string s = strings[i];
int res = FindMinDeletion(s);
Console.WriteLine(res);
}
}
static int FindMinDeletion(string s)
{
char[] chars = s.ToCharArray();
char pervious = chars[0];
int deletion = 0;
for (int i = 1; i < chars.Length; i++)
{
char next = chars[i];
if (pervious == next)
deletion += 1;
else
pervious = next;
}
return deletion;
}
}
Alternating Characters Java Solution
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'alternatingCharacters' function below.
*
* The function is expected to return an INTEGER.
* The function accepts STRING s as parameter.
*/
public static int alternatingCharacters(String s) {
// Write your code here
int currentChar = -1;
int toReturn = 0;
char[] chars = s.toCharArray();
for(int i = 0; i <chars.length; i++) {
if(currentChar == chars[i] && currentChar != -1) {
toReturn++;
} else {
currentChar = chars[i];
}
}
return toReturn;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int q = Integer.parseInt(bufferedReader.readLine().trim());
IntStream.range(0, q).forEach(qItr -> {
try {
String s = bufferedReader.readLine();
int result = Result.alternatingCharacters(s);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});
bufferedReader.close();
bufferedWriter.close();
}
}
Alternating Characters JavaScript Solution
function processData(input) {
var inputArr = input.split('\n');
var T = parseInt(inputArr.shift());
if(T<1 || T>10)
return;
for(var j=0;j<T; j++){
var i=0, noOfDels=0, k=0;
var str = inputArr[j], len=str.length;
if(len>100000)
continue;
while(i<len){
k=i+1;
while(str[i]==str[k]){
++noOfDels;
k++;
}
i=k;
}
console.log(noOfDels);
}
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
Alternating Characters Python Solution
N = int(input())
for i in range(N):
s = input()
lastchar = s[0]
cnt = 0
for char in s[1:]:
if(char == lastchar):
cnt += 1
else:
lastchar = char
print(cnt)
Other Solutions