Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Iterate through all string characters. If actual character i
is different then character i-1
then use character i
for next comparison. If they are not equal increment a deletion counter. Print the value of the counter.
I created solution in:
All solutions are also available on my GitHub.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.util.Scanner; public class AlternatingCharacters { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = Integer.parseInt(stdin.nextLine()); for(int i = 0; i < tests; i++) { String string = stdin.nextLine(); int deletions = 0; char c = string.charAt(0); for(int j = 1; j < string.length(); j++) { if(c == string.charAt(j)) { deletions++; } else { c = string.charAt(j); } } System.out.println(deletions); } stdin.close(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
function processData(input) { var lines = input.split("\n"); console.log(lines.slice(1, lines.length).map(deletions).join("\n")); } function deletions(s) { var last = s.charAt(0); var dels = 0; for(var i = 1; i < s.length; i++) { if(last === s.charAt(i)) { dels++; } else { last = s.charAt(i); } } return dels; } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); }); |
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import scala.io.Source object AlternatingCharacters extends App { val strings = Source.stdin.getLines().drop(1) println(strings.map(deletions).mkString("\n")) def deletions(s: String):Int = { var last = s.charAt(0) var dels = 0 s.drop(1).foreach { c => { if (last == c) { dels += 1 } else { last = c } } } dels } } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
def deletions(s) last = s[0] dels = 0 for i in 1..(s.length) do if last == s[i] dels += 1 else last = s[i] end end dels end var tests = gets.to_i tests.times do s = gets puts deletions(s) end |