Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- void purify(char *s) // A function to turn strings to all-lowercase letters
- {
- for(int i = 0; s[i] != '\0'; i++)
- {
- if(s[i] >= 'A' && s[i] <= 'Z')
- {
- s[i] += 32;
- }
- }
- }
- int remove_spaces(char *str)
- {
- int len = strlen(str);
- int newlen=0;
- int spaces = 0;
- for (int i = 0; i < len; i++)
- {
- if(str[i]!= ' ')
- {
- newlen++;
- }
- else if(str[i] == ' ')
- spaces++;
- }
- int index =0;
- for (int j = 0; j < len; j++)
- {
- if(str[j]!=' ')
- {
- str[index]=str[j];
- index++;
- }
- }
- str[newlen]='\0';
- return spaces;
- }
- int check_small_palindrome(char *s, int first, int last)
- {
- char *new_string = (char*)malloc(last-first+1+1); // +1 for '\0'
- int new_string_index = 0;
- for(int k = first; k <= last; k++)
- {
- new_string[new_string_index] = s[k];
- new_string_index++;
- }
- // new_string[last-first+1] = '\0';
- int spaces = remove_spaces(new_string);
- int len_new_string = last-first + 1;
- len_new_string -= spaces;
- for(int i = 0; i < len_new_string; i++)
- {
- if(new_string[i] != new_string[len_new_string-1])
- {
- free(new_string);
- return 0;
- }
- else
- len_new_string--;
- }
- free(new_string);
- return 1;
- }
- int isPalindrome(char *s, int *pass1, int *pass2)
- {
- purify(s);
- int len = strlen(s);
- int first = 0, last = len - 1;
- for(int i = 0; i < len; i++)
- {
- if(s[i] != ' ')
- {
- first = i;
- for(int j = last; j > i; j--)
- {
- if(s[i] == s[j] && s[i] != ' ' && s[j] != ' ')
- {
- last = j;
- if(check_small_palindrome(s, first, last))
- {
- *pass1 = first;
- *pass2 = last;
- return 1;
- }
- }
- }
- }
- }
- return 0;
- }
- void main()
- {
- // time complexity 'n'
- // get a char every time and compare the char with the new array
- // that holds everything except the char
- // the char can be replaced with ' '
- // char s[] = "I love anna aoi";
- // char s[] = "l";
- // char s[] = "I ' 'ove anna aoi";
- char s[] = "I anna plnas";
- int pass1, pass2;
- int result = isPalindrome(s, &pass1, &pass2);
- // printf("%s\n\n", s);
- printf("\nMoney Time: %d\n", result);
- printf("\n1: %d\n2: %d\n\n", pass1, pass2);
- }
Add Comment
Please, Sign In to add comment