2012年8月24日

UVa 353 - Pesky Palindromes


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

int N;
char all[100][1000];

int pal(char* tmp, int min, int max) {
  int i, l = max - min, flag = 1;
  for (i = min; i <= min + l / 2; i++)
    if (tmp[i] != tmp[max - i + min]) {
      flag = 0;
      break;
    }
  char temp[100];
  for (i = 0; i < l; i++)
    temp[i] = tmp[i + min];
  temp[i] = '\0';
  for (i = 0; i < N; i++)
    if (!strcmp(all[i], temp)) {
      flag = 0;
      break;
    }
  if (flag == 1) strcpy(all[N++], temp);
  return flag;
}

int main() {
  char tmp[100];
  while (scanf("%s", &tmp) == 1) {
    N = 0;
    int i, j, asc[129] = {0}, times = 0;
    for (i = 0; tmp[i]; i++) {
      if (!asc[tmp[i]]) {
        asc[tmp[i]] = 1;
        times++;
      }
      for (j = i + 1; tmp[j]; j++)
        if (i != j && pal(tmp, i, j)) times++;
    }
    printf("The string '%s' contains %d palindromes.\n", tmp, times);
  }
  return 0;
}

沒有留言:

張貼留言