-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWordBreakProblem.c
63 lines (52 loc) · 1.57 KB
/
WordBreakProblem.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// complexity O(n^2) for evaluating every sub-array approach
// complexity O(n log n) for sorting + binary search approach
// complexity O(n) for hashing approach, with space complexity O(n)
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define MAX(a,b) a > b ? a : b
#define ELEMENTS (16)
#define MAX_OUTPUT_SIZE (100)
int num_solutions = 0;
void Wordbreak(char *match, char **A, int dict_size, char *output)
{
if (strlen(match) == 0)
{
strcat(output, "\0");
printf("Solution = %s\n",output);
free(output);
num_solutions++;
return;
}
for (int i=0; i<dict_size; i++)
{
int len = strlen(A[i]);
bool full_match = true;
for (int j=0; j<len; j++)
{
if (match[j] != A[i][j])
{
full_match = false;
break;
}
}
if (full_match)
{
char *output_buffer = (char*)malloc(MAX_OUTPUT_SIZE*sizeof(char));
strcpy(output_buffer, output);
strcat(output_buffer, A[i]);
strcat(output_buffer, " ");
Wordbreak(&match[len], A, dict_size, output_buffer);
}
}
}
char output[MAX_OUTPUT_SIZE];
int main()
{
char *match = "Wordbreakproblem";
char *array[ELEMENTS] = { "this", "th", "is", "famous", "Word", "break", "b", "r", "e", "a", "k", "br", "bre", "brea", "ak", "problem" };
Wordbreak(match, array, ELEMENTS, &output[0]);
printf("\nfinished with %u solutions!\n", num_solutions);
return 0;
}