Skip to content

Instantly share code, notes, and snippets.

@hyunjun
Created December 11, 2014 02:32
Show Gist options
  • Save hyunjun/be576eaaa7ba3c5035a9 to your computer and use it in GitHub Desktop.
Save hyunjun/be576eaaa7ba3c5035a9 to your computer and use it in GitHub Desktop.
[hackerrank] alternating characters
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STR_LEN 100000
int num_of_deletion(const char const * s) {
if ( s == NULL || 0 == strlen(s) || MAX_STR_LEN < strlen(s) )
return 0;
int len = strlen(s);
int i = 0, cnt = 0;
char prev = *(s + 0);
for ( i = 1; i < len; ++i ) {
if ( prev == *(s + i) )
cnt += 1;
else
prev = *(s + i);
}
return cnt;
}
int main() {
int num_of_test_case = 0;
fscanf(stdin, "%d", &num_of_test_case);
int* test_cases = (int*) malloc(sizeof(int) * num_of_test_case);
int i = 0;
for ( i = 0; i < num_of_test_case; ++i ) {
char s[MAX_STR_LEN + 1];
memset(s, '\0', MAX_STR_LEN + 1);
fscanf(stdin, "%s", s);
printf("%d\n", num_of_deletion(s));
}
}
import sys
def num_of_deletion(s):
cnt = 0
prev = s[0]
for c in s[1:]:
if c == prev:
cnt += 1
else:
prev = c
return cnt
if __name__ == '__main__':
inp = []
for line in sys.stdin:
inp.append(line.strip())
for i in inp[1:]:
print num_of_deletion(i)
import java.util.Scanner;
public class Test {
public static int numOfDeletion(final String s) {
int cnt = 0;
char prev = s.charAt(0);
for ( int i = 1; i < s.length(); ++i ) {
char c = s.charAt(i);
if ( prev == c )
cnt += 1;
else
prev = c;
}
return cnt;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numOfTestCases = Integer.parseInt(sc.nextLine());
for ( int i = 0; i < numOfTestCases; ++i ) {
System.out.println(numOfDeletion(sc.nextLine()));
}
}
}
// https://www.hackerrank.com/challenges/alternating-characters
object Solution {
def numOfDeletion(s: String): Int = {
var cnt: Int = 0
var prev: Char = s(0)
for ( c <- s.drop(1) ) {
if ( prev == c )
cnt += 1
else
prev = c
}
cnt
}
def main(args: Array[String]) {
val inp = io.Source.stdin.getLines.drop(1)
for (i <- inp) println(numOfDeletion(i))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment