Skip to content

Commit 05a0762

Browse files
committed
added alternatingCharacters hackerrank solution
1 parent 5704242 commit 05a0762

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed

hackerRank/alternatingCharacters.js

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
// You are given a string containing characters and 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.
2+
3+
// Your task is to find the minimum number of required deletions.
4+
5+
// For example, given the string , remove an at positions and to make in deletions.
6+
7+
// Function Description
8+
9+
// Complete the alternatingCharacters function in the editor below. It must return an integer representing the minimum number of deletions to make the alternating string.
10+
11+
// alternatingCharacters has the following parameter(s):
12+
13+
// s: a string
14+
// Input Format
15+
16+
// The first line contains an integer , the number of queries.
17+
// The next lines each contain a string .
18+
19+
// Constraints
20+
21+
// Each string will consist only of characters and
22+
// Output Format
23+
24+
// For each query, print the minimum number of deletions required on a new line.
25+
26+
// Sample Input
27+
28+
// 5
29+
// AAAA
30+
// BBBBB
31+
// ABABABAB
32+
// BABABA
33+
// AAABBB
34+
// Sample Output
35+
36+
// 3
37+
// 4
38+
// 0
39+
// 0
40+
// 4
41+
42+
'use strict';
43+
44+
const fs = require('fs');
45+
46+
process.stdin.resume();
47+
process.stdin.setEncoding('utf-8');
48+
49+
let inputString = '';
50+
let currentLine = 0;
51+
52+
process.stdin.on('data', inputStdin => {
53+
inputString += inputStdin;
54+
});
55+
56+
process.stdin.on('end', _ => {
57+
inputString = inputString.replace(/\s*$/, '')
58+
.split('\n')
59+
.map(str => str.replace(/\s*$/, ''));
60+
61+
main();
62+
});
63+
64+
function readLine() {
65+
return inputString[currentLine++];
66+
}
67+
68+
// Complete the alternatingCharacters function below.
69+
function alternatingCharacters(s) {
70+
let count = 0;
71+
for (let i = 0; i < s.length - 1; i++) {
72+
let current = s[i];
73+
let next = s[i + 1];
74+
if (current === next) {
75+
count++;
76+
}
77+
}
78+
return count;
79+
}
80+
81+
function main() {
82+
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
83+
84+
const q = parseInt(readLine(), 10);
85+
86+
for (let qItr = 0; qItr < q; qItr++) {
87+
const s = readLine();
88+
89+
let result = alternatingCharacters(s);
90+
91+
ws.write(result + "\n");
92+
}
93+
94+
ws.end();
95+
}

0 commit comments

Comments
 (0)