最初はこう書いた
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int find(char *s, char *l) { | |
return (*l == '\0')?1:(*s == *l)?find(s+1, l+1):0; | |
} | |
char* mstrstr(char *s, char *l) { | |
return (*s == '\0')?0:find(s, l)?s:mstrstr(s+1,l); | |
} | |
#include <stdio.h> | |
int main(void) { | |
char *c = "abcdefghijklmnopq"; | |
char *s = "fgh"; | |
printf("%s\n", mstrstr(c, s)); | |
char *e = "cdefhg"; | |
printf("%d\n", mstrstr(c, e)); | |
return 0; | |
} |
関数2つも定義してる上に検索対象の文字列が\0のみの時に動作が(多分)異なる。これを書いた時点で経過時間30分。エンバグしたのが痛い
関数2つ定義してるのがどうにもじょうよわ感溢れて気持ち悪いので、return文を工夫してうまくまとめてみた
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
char* mstrstr(char *s, char *l) { | |
return (*l == '\0')?s:(*s == '\0')?0:(*s != *l)?mstrstr(s+1,l):mstrstr(s+1,l+1)?s:0; | |
} | |
#include <stdio.h> | |
int main(void) { | |
char *c = "abcdefghijklmnopq"; | |
char *s = "fgh"; | |
printf("%s\n", mstrstr(c, s)); | |
char *e = "cdefhg"; | |
printf("%d\n", mstrstr(c, e)); | |
char *n = ""; | |
printf("%s\n", mstrstr(c, n)); | |
return 0; | |
} |
ここまで1時間かかった……
これだと上で書いた状況でもstrstrと(多分)同じ値返してるし、これで多分あってる……よね?
一つ一つ進めていて効率が悪いんだけども、そこを効率よくしたり、これ以上短くする方法は考えつかなかった。
正直もう受験近いんでこういうことで時間を割く余裕も中々ないんですが。
0 件のコメント:
コメントを投稿