From ed37657c6cf6bf6e0b1b9a44b109b280c33f2424 Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Sun, 3 Sep 2017 10:17:11 +0800 Subject: [PATCH] Scramble string Signed-off-by: Leo Ma --- 087_scramble_string/Makefile | 2 + 087_scramble_string/scramble_string.c | 66 +++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 087_scramble_string/Makefile create mode 100644 087_scramble_string/scramble_string.c diff --git a/087_scramble_string/Makefile b/087_scramble_string/Makefile new file mode 100644 index 0000000..52cecd7 --- /dev/null +++ b/087_scramble_string/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test scramble_string.c diff --git a/087_scramble_string/scramble_string.c b/087_scramble_string/scramble_string.c new file mode 100644 index 0000000..1eb5c8a --- /dev/null +++ b/087_scramble_string/scramble_string.c @@ -0,0 +1,66 @@ +#include +#include +#include +#include + +/* The recursive way is quite simple. + * 1) break the string to two parts: + * s1[0..j] s1[j+1..n] + * s2[0..j] s2[j+1..n] + * 2) then + * isScramble(s1[0..j], s2[0..j]) && isScramble(s1[j+1..n], s2[j+1..n]) + * or + * isScramble(s1[0..j], s2[n - j - 1, n]) && isScramble(s1[j+1..n], s2[0..n - j]) + */ +#define N 128 + +static bool scramble(char *s1, int low1, int high1, char *s2, int low2, int high2) +{ + if (high1 - low1 != high2 - low2) { + return false; + } else if (!memcmp(s1 + low1, s2 + low2, high1 - low1 + 1)) { + return true; + } else { + int i, c1[N], c2[N]; + memset(c1, 0, N * sizeof(int)); + memset(c2, 0, N * sizeof(int)); + for (i = low1; i <= high1; i++) { + c1[s1[i]]++; + } + for (i = low2; i <= high2; i++) { + c2[s2[i]]++; + } + if (memcmp(c1, c2, N * sizeof(int))) { + return false; + } else { + int len = high1 - low1 + 1; + for (i = 1; i < len; i++) { + if (scramble(s1, low1, low1 + i - 1, s2, low2, low2 + i - 1) && + scramble(s1, low1 + i, high1, s2, low2 + i, high2)) { + return true; + } + if (scramble(s1, low1, low1 + i - 1, s2, high2 - i + 1, high2) && + scramble(s1, low1 + i, high1, s2, low2, high2 - i)) { + return true; + } + } + return false; + } + } +} + +static bool isScramble(char* s1, char* s2) { + int len1 = strlen(s1); + int len2 = strlen(s2); + return scramble(s1, 0, len1 - 1, s2, 0, len2 - 1); +} + +int main(int argc, char **argv) +{ + if (argc != 3) { + fprintf(stderr, "Usage: ./test s1 s2\n"); + exit(-1); + } + printf("%s\n", isScramble(argv[1], argv[2]) ? "true" : "false"); + return 0; +}