Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <assert.h>
- #include <limits.h>
- #include <math.h>
- #include <stdbool.h>
- #include <stddef.h>
- #include <stdint.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- char* readline();
- // Complete the palindromeIndex function below.
- int palindromeIndex(char* s) {
- int l=strlen(s), Eliminated=0, DelIdx=0, Found=0;
- for(int p=0; p<2 && Found==0; p++){
- Eliminated = 0;
- for(int i=0, j=l-1;i<l/2 && Eliminated < 2; i++, j--){
- // confronto l'i-esimo con l'omologo carattere j-esimo
- if (s[i] != s[j]){
- // sono diversi, quindi devo decidere quale eliminare
- if(p==0){
- if(s[i]==s[j-1]){
- // va eliminato j (prima passata)
- DelIdx = j;
- // ... ma i non deve cambiare al prossimo giro
- i--;
- } else {
- // va eliminato i (prima passata)
- DelIdx = i;
- // ma j non deve cambiare al prossimo giro
- j++;
- }
- } else {
- if(s[j]==s[i+1]){
- // va eliminato i (seconda passata)
- DelIdx = i;
- // ma j non deve cambiare al prossimo giro
- j++;
- } else {
- // va eliminato j (seconda passata)
- DelIdx = j;
- // ... ma i non deve cambiare al prossimo giro
- i--;
- }
- }
- Eliminated++;
- }
- }
- Found = (Eliminated == 1? 1: 0);
- }
- return (Eliminated != 1? -1: DelIdx);
- }
- int main()
- {
- FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
- char* q_endptr;
- char* q_str = readline();
- int q = strtol(q_str, &q_endptr, 10);
- if (q_endptr == q_str || *q_endptr != '\0') { exit(EXIT_FAILURE); }
- for (int q_itr = 0; q_itr < q; q_itr++) {
- char* s = readline();
- int result = palindromeIndex(s);
- fprintf(fptr, "%d\n", result);
- }
- fclose(fptr);
- return 0;
- }
- char* readline() {
- size_t alloc_length = 1024;
- size_t data_length = 0;
- char* data = malloc(alloc_length);
- while (true) {
- char* cursor = data + data_length;
- char* line = fgets(cursor, alloc_length - data_length, stdin);
- if (!line) { break; }
- data_length += strlen(cursor);
- if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; }
- size_t new_length = alloc_length << 1;
- data = realloc(data, new_length);
- if (!data) { break; }
- alloc_length = new_length;
- }
- if (data[data_length - 1] == '\n') {
- data[data_length - 1] = '\0';
- }
- data = realloc(data, data_length);
- return data;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement