DEV Community

Discussion on: Daily Coding Puzzles

Collapse
 
zenmumbler profile image
zenmumbler • Edited

Just to show, Day 3 in C, Time: O(n), Space: O(1), the result is processed in place. Of course, this one only works with ASCII…

Quick subquiz for anyone actually reading this: under what circumstances will this program crash or exhibit undefined behaviour?

#include <stdio.h>
#include <string.h>
#include <ctype.h>

void esrever(char *s, int from, int to) {
    while (from < to) {
        char temp = s[from];
        s[from] = s[to];
        s[to] = temp;
        from++;
        to--;
    }
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        return 1;
    }

    char *s = argv[1];
    int begin = 0, end = 0, len = strlen(s);

    do {    
        while (end < len && ! isspace(s[end])) {
            end++;
        }
        if (end - begin > 4) {
            esrever(s, begin, end - 1);
        }
        begin = end + 1;
        end = begin;
    } while (end < len);

    printf("%s\n", s);
}