2-5 any.c
squeezeに続いてテーブルを作っちゃう。なんか気に入った。
for入れ子にしなくていいあたりが。
ま、メモリは食うけど毎回s2をスキャンするよりは早いはず。
時間と空間のトレードオフですな。
/* * P59 演習2-5 * 文字列s2中の任意の文字に等しい文字列s1の最初の * 文字位置を返す関数any(s1, s2)を書け。ただし、一致 * する文字がなければ-1を返す。(標準ライブラリ関数strpbrk * は同じ働きをもつが、その位置へのポインタを返す。) * * 2007/06/23 arikui */ #include <limits.h> int any(char *s1, char *s2){ int idx = -1, i; char tbl[CHAR_MAX + 1] = {0}; for(i = 0; s2[i] != '\0'; ++i) tbl[s2[i]] = 1; for(i = 0; s1[i] != '\0'; ++i){ if (tbl[s1[i]]){ idx = i; break; } } return idx; } //Test Driver #include <stdio.h> int main(void){ int i; char *test_s1[] = {"hello, world!", NULL}; char *test_s2[] = {"way", NULL}; for(i = 0; test_s1[i] != NULL; ++i){ printf("%s < %s : %d\n", test_s1[i], test_s2[i], any(test_s1[i], test_s2[i])); } return 0; }